iOS any way to cancel all network requests

旧城冷巷雨未停 提交于 2019-12-11 08:34:53

问题


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?


回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/15755650/ios-any-way-to-cancel-all-network-requests

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!