iosobjective-cmultithreadingafhttprequestoperation

How to cancel AFHTTPRequestOperation?


I have Singleton class APIHTTPClient responsible for making Restful Call using AFHTTPRequestOperation** .i have a senario where user click a button to see a View and call APIHTTPClient to get the new data to display it in that view but the user can also click Back button to click another view and calling APIHTTPClient get new data for the new View.

How to Cancel the previous AFHTTPRequestOperation request when the user click Back to call another restful Request.

-(void)CallRemoteService:(int) iModuleID { static NSString * const BaseURLString = @"http://www.raywenderlich.com/demos/weather_sample/"; NSString *string = [NSString stringWithFormat:@"%@weather.php?format=xml", BaseURLString];

NSURL *url = [NSURL URLWithString:string];
NSURLRequest *request = [NSURLRequest requestWithURL:url];

AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];


// Make sure to set the responseSerializer correctly

// operation.responseSerializer = [AFXMLParserResponseSerializer serializer];

[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

    self.queue = [[NSOperationQueue alloc] init];

Solution

  • In your view controller, keep the reference to AFHTTPRequestOperation *operation and then on back pressed :

    [operation cancel]