Manage completion handler of NSURLSession from a custom class

跟風遠走 提交于 2020-01-03 00:22:07

问题


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"];

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;
}

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


回答1:


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

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

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);
    }];

Now in ViewController.h just conform to the Protocol

@inteface ViewController:UIViewController<LoginNetworkHelperResponseDelegate>
…
@end

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

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

Now just implement the following code to initiate the LoginRequest.

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

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.

Regards,

Amit



来源:https://stackoverflow.com/questions/25484548/manage-completion-handler-of-nsurlsession-from-a-custom-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!