如何在alamofire中设置请求超时?
Posted
技术标签:
【中文标题】如何在alamofire中设置请求超时?【英文标题】:how to set request timeout in alamofire? 【发布时间】:2017-07-11 18:09:27 【问题描述】:我尝试使用 NSURLSession,但现在我想使用 Alamofire。
【问题讨论】:
【参考方案1】:这种方法在 swift 3 上对我有用
let manager : SessionManager =
let config = URLSessionConfiguration.default
config.timeoutIntervalForRequest = 15
config.timeoutIntervalForResource = 15
let mgr = Alamofire.SessionManager(configuration: config)
return mgr
()
从https://github.com/Alamofire/Alamofire#session-manager得到它
【讨论】:
【参考方案2】:如果您想要自定义超时,请在请求中设置值,或使用自定义配置创建自定义 URLSession
:alamofire documentation
let configuration = URLSessionConfiguration.default
configuration.timeoutIntervalForRequest = 10 // seconds
configuration.timeoutIntervalForResource = 10
let sessionManager = Alamofire.SessionManager(configuration: configuration)
//或
var request = URLRequest(url: URL(string: "myApi.com/Api/login")!, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 20)
request.httpMethod = "GET"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
Alamofire.request("https://httpbin.org/get").responseJSON response in
print(response)
if let json = response.result.value
print("JSON: \(json)")
【讨论】:
【参考方案3】:在 AppDelegate 的 application(_:didFinishLaunchingWithOptions:)
方法中调用此函数。
func configureAlamofire()
Alamofire.SessionManager.default.session.configuration.timeoutIntervalForRequest = 15 // in seconds
Alamofire.SessionManager.default.session.configuration.timeoutIntervalForResource = 15 // in seconds
【讨论】:
【参考方案4】:let manager = Alamofire.SessionManager.default
manager.session.configuration.timeoutIntervalForRequest = 120
manager.request("yourUrl", method: .post, parameters: ["parameterKey": "value"])
.responseJSON
response in
switch (response.result)
case .success:
//do json stuff
break
case .failure(let error):
if error._code == NSURLErrorTimedOut
//timeout here
print("\n\nAuth request failed with error:\n \(error)")
break
【讨论】:
【参考方案5】:对于新版本的Alamofire(5.0.0以上),这样写,
AF.sessionConfiguration.timeoutIntervalForRequest = 120
AF.sessionConfiguration.timeoutIntervalForResource = 120
【讨论】:
以上是关于如何在alamofire中设置请求超时?的主要内容,如果未能解决你的问题,请参考以下文章