Is it possible to cancel an
NSURLConnection
started withsendAsynchronousRequest:queue:completionHandler:
?Why doesn't
sendAsynchronousRequest:queue:completionHandler:
return theNSURLConnection
object it creates so that I can cancel it?
Asked
Active
Viewed 3,905 times
12

ma11hew28
- 121,420
- 116
- 450
- 651
1 Answers
5
EDIT - Since my provided answer seems to have been wrong, you should check out the following related question and its answers:
How can I cancel an asynchronous call through NSURLConnection sendAsynchronousRequest?
Old answer:
In your header of your class (e.g. ViewController), declare an operation queue:
NSOperationQueue *downloadOperationQueue;
To download a file call something like the following:
downloadOperationQueue = [[NSOperationQueue alloc] init];
NSURLRequest *fileRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.google.com/images/nav_logo114.png"]
cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
timeoutInterval:10];
[NSURLConnection sendAsynchronousRequest:fileRequest
queue:downloadOperationQueue
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSLog(@"download successful");
}];
To cancel the download later on call:
[downloadOperationQueue cancelAllOperations];
-
14According to the [doc](http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSURLConnection_Class/Reference/Reference.html): "...queue: The operation queue to which the handler block is dispatched when the request completes or failed". ie: the queue paramater is the queue that handles the completion block, not the queue that takes care of the request itself – Thomas Feb 05 '13 at 21:21
-
WTF? it will not cancel the request :D – l0gg3r Sep 22 '14 at 07:27
-
Yes. That's why I edited the answer and provided a link to another answer. – gchbib Sep 24 '14 at 10:53
-
Yes, the old answer just set isCancelled to Yes and you need to manually check and behave accordingly :/ – Skodik.o Aug 09 '16 at 12:18