从自定义类管理NSURLSession的完成处理程序 [英] Manage completion handler of NSURLSession from a custom class

查看:46
本文介绍了从自定义类管理NSURLSession的完成处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序的一部分用于根据提供给用户的唯一代码为用户创建登录检查.为了使我的应用程序结构正确,我创建了一个Network Helper类来处理所有网络操作.这是我从控制器类(ViewController.m)调用助手类的方法.

Part of my app deals with creating a Login check for the user based on a unique code provided to them. To make my application properly structured, I've created a network Helper class to deal with all network operations. Here's How i call my helper class from the controller class (ViewController.m).

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

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

My LoginNetworkHelper class does the following tasks(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视图的控制器类之间进行通信.我需要基于从服务器返回的数据在主视图上进行一些更改,该数据只能从异步运行的完成处理程序访问.有没有更好的方法来管理所有网络任务,同时仍然能够引用从中调用它们的主控制器的对象.预先感谢

So my basic question is how to communicate between my completion handler of NSURLSession and my controller class which is linked to my view of Login. I need to change something on the main view based on the data returned from the server which is only accessible from the completion handler which runs asynchronously. Is there a better way to manage all network tasks while still being able to reference objects of the main controller from which they are called. Thanks in advance

推荐答案

您可以通过向LoginNetworkHelper.h类添加协议来实现通信.

You can achieve communication by adding a Protocol to LoginNetworkHelper.h class.

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

将Delegate变量添加到LoginNetworkHelper.h类中

Add the Delegate Variable to your LoginNetworkHelper.h class

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

现在将以下代码添加到完成处理程序中.

Now Add the following code to your completion Handler.

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中仅符合协议

Now in ViewController.h just conform to the Protocol

@inteface ViewController:UIViewController<LoginNetworkHelperResponseDelegate>
…
@end

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

And implement the protocol Method didFininshRequestWithJson:responseJson in ViewController.m

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

现在只需实现以下代码即可启动LoginRequest.

Now just implement the following code to initiate the LoginRequest.

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

一旦完成处理程序被调用,它将使用收到的json响应调用Delegate方法.也可以使用通知来实现.

As soon as the Completion Handler is invoked it will invoke the Delegate method with received json response. This can also be achieved using Notification.

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

Do let me know if you face any issues.

此致

授予

这篇关于从自定义类管理NSURLSession的完成处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆