Jason Zhao
Jason Zhao

Reputation: 1288

iOS any way to cancel all network requests

I'm doing the app update module. What I want to do is:

if there is a newer version detect, prompt user update AND at the same time, cancel all network requests if there is. The request may created by AFNETWORK, may created like [NSURLConnection sendSynchronousRequest:returningResponse:error:], all kind of network request, just cancel them all. Can I?

Upvotes: 1

Views: 2727

Answers (3)

dpassage
dpassage

Reputation: 5453

In the comments, OP says that the reason he wants to do this is because he's worried some other part of the app will try to access a network API that's no longer available.

If that's the case, the best way to do this is for the other parts of your app to provide an API that your part, the updater, can call to say "abort everything!". This has a couple of advantages:

  • If the other parts of the app start using BGNetworking (which will be much better than AFNetworking when it comes out next year), your updater code will still work.
  • It gives the other parts of the app the opportunity to do any cleanup they might want to. For instance, they might just give up on an API call instead of retrying it because something went wrong.

It sounds like this updater component isn't one that can be designed independently of the rest of the application.

Upvotes: 0

sixthcent
sixthcent

Reputation: 1160

Connections created using + (NSData *)sendSynchronousRequest:(NSURLRequest *)request returningResponse:(NSURLResponse **)response error:(NSError **)error cannot be canceled. If you called it from a background thread, you may be able to kill the thread itself.

A better approach would be to use NSOperationQueue and initiate network connections from NSOperation objects added to the queue. Optionally, you can create a subclass of NSOperation and make each instance observe a custom event notification with its cancel method as the target. With this approach, you will just need to post the custom notification to trigger a cancel to all instances of your operations and their associated network connections.

Upvotes: 1

borrrden
borrrden

Reputation: 33421

If you are using AFHTTPClient then you can get a hold of its operation queue and cancel all of the operations on it.

However, unless you have a list of all the NSURLConnection objects that you have created, I am not aware of a way to simply cancel all NSURLConnection objects.

Upvotes: 0

Related Questions