如何使用 AFNetworking 设置超时 [英] How to set a timeout with AFNetworking

查看:36
本文介绍了如何使用 AFNetworking 设置超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的项目正在使用 AFNetworking.

My project is using AFNetworking.

https://github.com/AFNetworking/AFNetworking

如何拨出超时时间?没有互联网连接的自动取款机在大约 2 分钟内不会触发失败块.太长了....

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.

这篇关于如何使用 AFNetworking 设置超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆