从自定义类pipe理NSURLSession的完成处理程序

我的应用程序的一部分处理基于提供给他们的唯一代码为用户创build一个login检查。 为了使我的应用程序结构合理,我创build了一个networking助手类来处理所有的networking操作。 这里是我如何从控制器类(ViewController.m)调用我的助手类。

[[LoginNetworkHelper alloc] loginBasedOnPatientId:@"abc"];

我的LoginNetworkHelper类执行以下任务(LoginNetworkhelper.m)

 - (BOOL)loginBasedOnPatientId:(NSString *)patientId { NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://test.php"]]; [request setHTTPMethod:@"POST"]; //creating json string to send to server NSDictionary *patientData = [NSDictionary dictionaryWithObjectsAndKeys:@"002688727",@"value",@"prem_key_id",@"name", nil]; NSMutableArray *dataArr = [[NSMutableArray alloc] init]; [dataArr addObject:patientData]; NSError *error; NSData *jsonData2 = [NSJSONSerialization dataWithJSONObject:dataArr options:NSJSONWritingPrettyPrinted error:&error]; NSString *jsonString = [[NSString alloc] initWithData:jsonData2 encoding:NSUTF8StringEncoding]; NSString *postData = [NSString stringWithFormat:@"message=%@",jsonString]; [request setHTTPBody:[postData dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]]; NSURLSessionDataTask *dataTask = [self.session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]; NSLog(@"%@",json); }]; [dataTask resume]; return TRUE; } 

所以我的基本问题是如何在NSURLSession完成处理程序和链接到我的Login视图的控制器类之间进行通信。 我需要根据从服务器返回的数据来改变主视图上的某些东西,这些数据只能从asynchronous运行的完成处理程序中访问。 有没有更好的方法来pipe理所有的networking任务,同时仍然可以引用它们被调用的主控制器的对象。 提前致谢

您可以通过在LoginNetworkHelper.h类中添加一个协议来实现通信。

 @protocol LoginNetworkHelperResponseDelegate <NSObject> @required -(void)didFininshRequestWithJson:(NSDictionary *)responseJson; @end 

将委托variables添加到您的LoginNetworkHelper.h类

 @property (nonatomic,strong) NSObject < LoginNetworkHelperResponseDelegate > *delegate; 

现在将下面的代码添加到您的完成处理程序。

 NSURLSessionDataTask *dataTask = [self.session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]; //Code Added Start [self.delegate didFininshRequestWithJson:json]; //Code Added Ends NSLog(@"%@",json); }]; 

现在在ViewController.h中只是遵守协议

 @inteface ViewController:UIViewController<LoginNetworkHelperResponseDelegate> … @end 

并在ViewController.m中实现协议Method didFininshRequestWithJson:responseJson

 -(void)didFininshRequestWithJson:(NSDictionary *)responseJson { //Process the responseJson; } 

现在只需实现下面的代码来启动LoginRequest。

 LoginNetworkHelper *loginNetHelper = [[LoginNetworkHelper alloc]init]; loginNetHelper.delegate = self; [loginNetHelper loginBasedOnPatientId:@"abc"]; 

一旦完成处理程序被调用,它将调用委托方法与收到的JSON响应。 这也可以通过使用通知来实现。

如果您遇到任何问题,请告诉我。

问候,

阿米特