如何在alamofire中设置请求超时?

时间:2017-07-11 18:09:28

标签: swift alamofire

我尝试使用NSURLSession,但现在我想使用Alamofire。

5 个答案:

答案 0 :(得分:3)

这种方法对我来说非常有用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

答案 1 :(得分:2)

在AppDelegate的application(_:didFinishLaunchingWithOptions:)方法中调用此函数。

func configureAlamofire() {
    Alamofire.SessionManager.default.session.configuration.timeoutIntervalForRequest = 15 // in seconds
    Alamofire.SessionManager.default.session.configuration.timeoutIntervalForResource = 15 // in seconds
}

答案 2 :(得分:2)

如果您想要自定义超时,请在请求中设置值,或使用自定义配置创建自定义URLSessionalamofire documentation

let configuration = URLSessionConfiguration.default
configuration.timeoutIntervalForRequest = 10 // seconds
configuration.timeoutIntervalForResource = 10
let sessionManager = Alamofire.SessionManager(configuration: configuration)

// OR

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 :(得分:1)

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
            }
        }

答案 4 :(得分:0)

对于Alamofire的新版本(5.0.0以上),这样写,

AF.sessionConfiguration.timeoutIntervalForRequest = 120
AF.sessionConfiguration.timeoutIntervalForResource = 120