How to implement delegate in place of notification

2019-09-14 17:26发布

问题:

## NetworkClass

-(void)getResponse:(NSString *)url{

    NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
    [urlRequest setHTTPMethod:@"GET"];
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];

    NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];

    NSURLSessionDataTask *task = [session dataTaskWithRequest: urlRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        //check if we encountered an error
        if(error != nil){
            NSLog(@"%@", [error localizedDescription]);
        }else{
            //get and check the HTTP status code
            NSInteger HTTPStatusCode = [(NSHTTPURLResponse *)response statusCode];
            if (HTTPStatusCode != 200) {
                NSLog(@"HTTP status code = %ld", (long)HTTPStatusCode);
            }

            [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                if(data != nil){
                    NSError *parseError = nil;
                    NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];

                    [[NSNotificationCenter defaultCenter] postNotificationName:@"ReloadNotification"
                                                                        object:self
                                                                      userInfo:responseDictionary];
                    NSLog(@"The response is - %@",responseDictionary);


                }
            }];
        }
    }];


    [task resume];

}

ViewController

-(void)viewDidLoad
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notifyReload:) name:@"ReloadNotification" object:nil];
}

Here I have communicated to the viewcontroller that response has come from server and kindly reflect the response on view controller by using NSNOTIFICATION .I actually want to implement the same thing through delegates .I am a new programmer and trying to learn delegates but not able to understand the concepts ,kindly explain with code that how the same task can be done through delegates.Thanks in advance!

回答1:

You can do using callback through blocks:

Declared method using block :

-(void)getResponse:(NSString *)url AndWithCallback:(void(^)(BOOL success, id responseObject))callback{
   if(data != nil){
       callback(YES,@"Your object");
   }
   else{
       callback(NO,@"pass nil");
   }
}

Invoke Method :

[self getResponse:@"" AndWithCallback:^(BOOL success, id responseObject) {
        NSLog(@"%@",responseObject);
    }];