在 Alamofire 中设置超时

编程入门 行业动态 更新时间:2024-10-10 17:31:04
本文介绍了在 Alamofire 中设置超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我使用的是 Alamofire 4.0.1 并且我想为我的请求设置超时.我尝试了这个问题中给出的解决方案:

I am using Alamofire 4.0.1 and I want to set a timeout for my request. I tried the solutions gived in this question:

在第一种情况,它抛出一个NSURLErrorDomain(超时设置正确):

In the first case, it throws a NSURLErrorDomain (timeout is set correctly):

let configuration = URLSessionConfiguration.default configuration.timeoutIntervalForRequest = 10 let sessionManager = Alamofire.SessionManager(configuration: configuration) sessionManager.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(" Auth request failed with error: (error)") break } }

第二种情况,超时没有被替换,仍然设置为60秒.

In the second case, the time out is not replaced and still set as 60 seconds.

let manager = Alamofire.SessionManager.default manager.session.configuration.timeoutIntervalForRequest = 10 manager.request("yourUrl", method: .post, parameters: ["parameterKey": "value"])

我在 ios 10.1 中运行

我的代码:(它不起作用)

let configuration = URLSessionConfiguration.default configuration.timeoutIntervalForRequest = 10 // seconds configuration.timeoutIntervalForResource = 10 let alamoFireManager = Alamofire.SessionManager(configuration: configuration) alamoFireManager.request("my_url", method: .post, parameters: parameters).responseJSON { response in switch (response.result) { case .success: //Success.... break case .failure(let error): // failure... break } }

解决了 Alamofire github 线程: Alamofire 4.3.0设置超时抛出 NSURLErrorDomain 错误 #1931

推荐答案

基于@kamal-thakur 的回复.

Based in @kamal-thakur response.

Swift 3:

var request = URLRequest(url: NSURL.init(string: "YOUR_URL") as! URL) request.httpMethod = "POST" request.setValue("application/json", forHTTPHeaderField: "Content-Type") request.timeoutInterval = 10 // 10 secs let postString = "param1=(var1)&param2=(var2)" request.httpBody = postString.data(using: .utf8) Alamofire.request(request).responseJSON { response in // do whatever you want here }

更多推荐

在 Alamofire 中设置超时

本文发布于:2023-11-26 02:12:41,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1632234.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Alamofire

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!