且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

iOS以任何方式取消所有网络请求

更新时间:2022-01-04 04:52:46

使用 +(NSData *)sendSynchronousRequest:(NSURLRequest *)requestingingResponse创建的连接:(NSURLResponse **)响应错误:(NSError **)错误无法取消。如果从后台线程调用它,则可以杀死该线程本身。

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.

更好的方法是使用NSOperationQueue并从添加到队列中的NSOperation对象启动网络连接。 (可选)您可以创建NSOperation的子类,并使每个实例以其 cancel 方法为目标来观察自定义事件通知。使用这种方法,您只需要发布自定义通知即可触发所有操作实例及其关联的网络连接的取消。

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.