Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cancel NSURLConnection started with sendAsynchronousRequest:queue:completionHandler:?

  1. Is it possible to cancel an NSURLConnection started with sendAsynchronousRequest:queue:completionHandler:?

  2. Why doesn't sendAsynchronousRequest:queue:completionHandler: return the NSURLConnection object it creates so that I can cancel it?

like image 301
ma11hew28 Avatar asked May 28 '12 20:05

ma11hew28


1 Answers

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];
like image 129
thgc Avatar answered Jan 17 '23 10:01

thgc