如何使用AFNetworking设置超时

问题描述:

我的项目正在使用AFNetworking。

My project is using AFNetworking.

https://github.com/ AFNetworking / AFNetworking

如何拨打超时?在没有互联网连接的情况下,故障块不会触发感觉约2分钟。 Waay to long ....

How do I dial down the timeout? Atm with no internet connection the fail block isn't triggered for what feels like about 2 mins. Waay to long....

更改超时间隔几乎肯定不是解决您所描述问题的最佳方案。相反,看起来你真正想要的是HTTP客户端处理网络无法访问,不是吗?

Changing the timeout interval is almost certainly not the best solution to the problem you're describing. Instead, it seems like what you actually want is for the HTTP client to handle the network becoming unreachable, no?

AFHTTPClient 已经有一个内置机制让你知道什么时候网络连接丢失, -setReachabilityStatusChangeBlock:

AFHTTPClient already has a built-in mechanism to let you know when internet connection is lost, -setReachabilityStatusChangeBlock:.

请求在慢速网络上需要很长时间。最好相信iOS知道如何处理慢速连接,并告诉它与之间没有连接的区别。

Requests can take a long time on slow networks. It's better to trust iOS to know how to deal slow connections, and tell the difference between that and having no connection at all.

为了扩展我的理由,为什么应该避免在这个线程中提到的其他方法,这里有一些想法:

To expand on my reasoning as to why other approaches mentioned in this thread should be avoided, here are a few thoughts:


  • 请求可以在他们开始之前被取消。排队请求不能保证它何时实际启动。

  • 超时间隔不应取消长时间运行的请求 - 尤其是POST。想象一下,如果您尝试下载或上传100MB视频。如果请求在慢速3G网络上尽可能地进行,那么为什么如果它比预期花费的时间更长,你会不必要地停止它?

  • performSelector :afterDelay:... 在多线程应用程序中可能很危险。这开启了自己的模糊和难以调试的竞争条件。

  • Requests can be cancelled before they're even started. Enqueueing a request makes no guarantees about when it actually starts.
  • Timeout intervals shouldn't cancel long-running requests—especially POST. Imagine if you were trying to download or upload a 100MB video. If the request is going along as best it can on a slow 3G network, why would you needlessly stop it if it's taking a bit longer than expected?
  • Doing performSelector:afterDelay:... can be dangerous in multi-threaded applications. This opens oneself up to obscure and difficult-to-debug race conditions.