gpt4 book ai didi

ios - swift 2.1 alamofire超时方法

转载 作者:搜寻专家 更新时间:2023-10-30 22:18:57 26 4
gpt4 key购买 nike

我对 alamofire 超时方法有疑问,首先,我的英语可能不够好,无法让你们理解我说的话......但我会厌倦解释我的问题

在我的项目中,我使用了 alamofire,出于某种原因,我需要确保我的应用程序在连接不良的区域工作。所以我在考虑使用超时方法。

我看到有人说,用解决方案一:

let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.timeoutIntervalForRequest = 2 // seconds
self.alamofireManager = Alamofire.Manager(configuration: configuration)
self.alamofireManager!.request(.GET, "http://example.com/")
.response { (request, response, data, error) in

将解决问题,但就我而言,我看到调试区域说我的请求是“取消”

所以我尝试了我在这里看到的另一种解决方案(stackoverflow)解决方案 2:

let manager = Alamofire.Manager.sharedInstance
manager.session.configuration.timeoutIntervalForRequest = 5
manager.request(.POST, url, parameters: params, encoding: .JSON, headers: nil).response(queue: dispatch_get_main_queue()) { (Request, res, data, error) -> Void in{}

此方法似乎应该有效,但只有当我让我的应用程序进入后台并 react 我的应用程序时,调试区域显示请求“超时”,否则调试区域不显示任何内容,除非我将其切换到后台并 react 应用程序。

我正在使用 Xcode 7.1 和 ios 9.0

更新:如果我使用解决方案 2 ,如果我让 requesttimeout = 5 ,调试区域将显示“超时错误”,但它需要超过 5 秒......有时它会显示大约 30 秒,但有时会超过 1 分钟...... ..

更新 2:我发现了问题所在。问题是,如果您使用 reachabilty 框架来检测连接状态,那么系统可能会先检测到连接是否打开,然后它会在 isReachable 之后显示请求超时(最多可能需要 1 分钟)。

最佳答案

基于 NSURLSessionConfiguration Class Reference

This property determines the request timeout interval for all tasks within sessions based on this configuration. The request timeout interval controls how long (in seconds) a task should wait for additional data to arrive before giving up. The timer associated with this value is reset whenever new data arrives. When the request timer reaches the specified interval without receiving any new data, it triggers a timeout.

只要有新数据到达,计时器就会重置,这就是为什么您有不同的错误时间。

你也可以为请求再设置一个参数:

manager.session.configuration.timeoutIntervalForResource = 5

关于ios - swift 2.1 alamofire超时方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33865843/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com