Handle timeout with Alamofire

后端 未结 9 1697
暗喜
暗喜 2020-12-01 05:24

Is it possible to add timeout handler for Alamofire request?

In my project I use Alamofire this way:

init() {
    let configuration = NSURLSessionCon         


        
9条回答
  •  醉酒成梦
    2020-12-01 05:48

    For Swift 3.x / Swift 4.0 / Swift 5.0 users with Alamofire >= 5.0

    Used request modifier to increase and decrease the timeout interval.

    Alamofire's request creation methods offer the most common parameters for customization but sometimes those just aren't enough. The URLRequests created from the passed values can be modified by using a RequestModifier closure when creating requests. For example, to set the URLRequest's timeoutInterval to 120 seconds, modify the request in the closure.

    var manager = Session.default
     manager.request(urlString, method: method, parameters: dict, headers: headers, requestModifier: { $0.timeoutInterval = 120 }).validate().responseJSON { response in
    

    OR

    RequestModifiers also work with trailing closure syntax.

    var manager = Session.default
         manager.request("https://httpbin.org/get") { urlRequest in
        urlRequest.timeoutInterval = 60
        urlRequest.allowsConstrainedNetworkAccess = false
    }
    .response(...)
    

    You can also check it here

提交回复
热议问题