0

I have the following block which performs a request in the background.
How may I cancel this request before it has completed?

    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(queue, ^{
        NSData *thumbnailData = [NSURLConnection sendSynchronousRequest:request];
        ...
    });
Egil
  • 4,265
  • 4
  • 20
  • 13
  • just as preference - i use NSInvocation and queues to handle seperate threads, however, yeah you need to do async request not sync. – theiOSDude May 22 '11 at 20:46

3 Answers3

9

You can't cancel once you've dispatched...

You can use a workaround, like:

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
__block BOOL isCanceled = NO;
dispatch_async(queue, ^{

    if (isCanceled)
        return;

    NSData *thumbnailData = [NSURLConnection sendSynchronousRequest:request];
    ...
});
amattn
  • 10,045
  • 1
  • 36
  • 33
5

You can use the higher level "NSOperationQueue", after adding the operation to queue, then you can cancelAllOperations.

Paradise
  • 558
  • 6
  • 17
4

You can't. You have to use the asynchronous interface of NSURLConnection to be able to cancel requests.

omz
  • 53,243
  • 5
  • 129
  • 141
  • Thanks - what if it is NSOperation? Does this change anything? – Egil May 22 '11 at 20:19
  • 1
    No, the method is called _synchronous_ for a reason: it blocks the calling thread until it's completed. It doesn't matter if you use NSOperation, GCD or NSThread. To be able to cancel requests, you have to implement the delegate methods of `NSURLConnection`, like `connection:didReceiveData:` etc. (see the documentation). Then you can use the `cancel` method before all data has been loaded. – omz May 22 '11 at 20:28