Alamofire超时在Swift 3中不起作用 [英] Alamofire timeout not working in Swift 3
问题描述
我正在使用Alamofire进行网络请求,并希望添加超时.但是Alamofire的功能无法正常工作.当我编写以下代码时,什么都没有发生
I am using Alamofire for network request and want to add timeout. But Alamofire's function is not working. Nothing happens when I write the following code
let manager = Alamofire.SessionManager.default
manager.session.configuration.timeoutIntervalForRequest = 1 // not working, 20 secs normally (1 just for try)
manager.request(url, method: method, parameters: params)
.responseJSON { response in
print(response)
...
当我在没有Alamofire的情况下尝试进行网络请求时,超时成功运行.但是还有其他错误.
When I try without Alamofire for network request, timeout working successfully. But there are other mistakes.
var request = URLRequest(url: URL(string: url)!)
request.httpMethod = "post"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.timeoutInterval = 1 // 20 secs normally (1 just for try)
request.httpBody = try! JSONSerialization.data(withJSONObject: params!)
...
那么,如何在Swift 3中为Alamofire添加超时?
推荐答案
最后,我找到了此答案的解决方案: https://stackoverflow.com/a/44948686/7825024
Finally I found a solution to this answer: https://stackoverflow.com/a/44948686/7825024
当我添加函数时,此配置代码不起作用,但是当我将其添加到 AppDelegate!
This configuration code does not work when I add my function, but it works when I add it to AppDelegate!
AppDelegate.swift
import UIKit
var AFManager = SessionManager()
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let configuration = URLSessionConfiguration.default
configuration.timeoutIntervalForRequest = 5 // seconds
configuration.timeoutIntervalForResource = 5 //seconds
AFManager = Alamofire.SessionManager(configuration: configuration)
return true
}
...
}
示例:
AFManager.request("yourURL", method: .post, parameters: parameters).responseJSON { response in
...
}
这篇关于Alamofire超时在Swift 3中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!