Alamofire超时无法在Swift 3中运行

问题描述 投票:0回答:2

我正在使用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添加超时?

json swift timeout alamofire
2个回答
2
投票

最后我找到了这个答案的解决方案: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
    ...
}

0
投票

在将URLSessionConfiguration添加到URLSession之后,您无法修改Alamofire.SesssionManager.default.session.configuration的值,因此尝试操作SessionManager将始终失败。要正确更改配置值,请按照Alamofire文档实例化您自己的var defaultHeaders = Alamofire.SessionManager.defaultHTTPHeaders defaultHeaders["DNT"] = "1 (Do Not Track Enabled)" let configuration = URLSessionConfiguration.default configuration.httpAdditionalHeaders = defaultHeaders let sessionManager = Alamofire.SessionManager(configuration: configuration) 。例如:

qazxswpoi
© www.soinside.com 2019 - 2024. All rights reserved.