json - Alamofire 超时在 Swift 3 中不起作用

标签 json swift timeout alamofire

我正在使用 Alamofire 进行网络请求并希望添加超时。但是Alamofire 的功能不起作用。当我写下面的代码时没有任何反应

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 进行网络请求时,超时成功。但还有其他错误。

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

当我添加我的函数时,此配置代码不起作用,但当我将它添加到 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
    ...
}

关于json - Alamofire 超时在 Swift 3 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46746405/

相关文章:

ios - 为什么 webkit view 连接不上 App Store

ios - 使用 .Value 和 .ChildAdded 检索数据

ios - AVAudioEngine 输入上的点击麦克风不起作用

c - 为什么从 bash 脚本调用超时程序会导致 tcsetattr 挂起?

javascript - 让 JSON 对象在 NodeJS 中工作的问题

javascript - 舍入 Json 对象的所有对象中的小数值

timeout - 在 Apache JMeter 中配置响应超时

http - http.TimeoutHandler返回,但是handlerfunc继续运行

Javascript 将 JSON 对象值作为单选按钮或列表的文本

java - Firebase 数据库 Android - 将具有不同结构的 datasnapshot 子级映射到 java 对象