4

I'm trying to add in the ability to cancel all current asynchronous requests when the user leaves the view or when they initiate a new request. I know where to put the code, but I'm not quite sure how to actually cancel the request. From my research, I know that NSURLConnection has a cancel method, but I'm calling my requests using asynchronous blocks. Below is my code - any help is greatly appreciated!

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setHTTPMethod:@"GET"];
[request setURL:[NSURL URLWithString:[kEndpointEvents stringByAppendingString:arguments]]];

//Send an asynchronous request so it doesn't pause the main thread
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {

    NSHTTPURLResponse *responseCode = (NSHTTPURLResponse *)response;

    //Do stuff

}];
rebello95
  • 8,486
  • 5
  • 44
  • 65

1 Answers1

1

It's not possible to cancel an ongoing request when using the convenience methods +sendAsynchronousRequest:queue:completionHandler or +sendSynchronousRequest:returningResponse:error:.

If you want cancellation, implement the methods in the delegate NSURLConnectionDataDelegate, and build the data yourself from the callbacks. Doing that will give you control over the connection object and you can call -cancel on it anytime.

Anurag
  • 140,337
  • 36
  • 221
  • 257
  • Do you have a library, tutorial, or example you'd recommend? – rebello95 Jul 17 '14 at 03:07
  • 1
    Checkout https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/URLLoadingSystem/Tasks/UsingNSURLConnection.html, http://stackoverflow.com/questions/9577317/nsurlconnection-delegate-method, http://codewithchris.com/tutorial-how-to-use-ios-nsurlconnection-by-example/ – Anurag Jul 17 '14 at 03:28
  • 1
    Just FYI to anyone else wondering: After doing some research, I ended up using the AFNetworking library. It is a very well designed and up-to-date library that allows for connection cancelling and much more. – rebello95 Jul 22 '14 at 17:34
  • @rebello95, Could you still share some implementation for the library or how you finished solving the issue? – kitimenpolku Mar 18 '15 at 08:19
  • @kitimenpolku just look at their documentation and/or tutorials. There is a ton of info on it out there. – rebello95 Mar 18 '15 at 13:53