Handle timeout with Alamofire

后端 未结 9 1648
暗喜
暗喜 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:57

    Swift 3.x

    class NetworkHelper {
        static let shared = NetworkHelper()
        var manager: SessionManager {
            let manager = Alamofire.SessionManager.default
            manager.session.configuration.timeoutIntervalForRequest = 10
            return manager
        }
        func postJSONData( withParams parameters: Dictionary<String, Any>, toUrl urlString: String, completion: @escaping (_ error: Error,_ responseBody: Dictionary<String, AnyObject>?)->()) {
            manager.request(urlString, method: .post, parameters: parameters, encoding: JSONEncoding.default).responseJSON { response in 
                if let error = response.result.error {
                    if error._code == NSURLErrorTimedOut {
                        print("Time out occurs!")
                    }
                }
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-01 05:59

    Swift 3

    The accepted answer didn't work for me.

    After a lot of research, I did it like this:

    let manager = Alamofire.SessionManager.default
    manager.session.configuration.timeoutIntervalForRequest = 120
    
    manager.request("yourUrl", method: .post, parameters: ["parameterKey": "value"])
    
    0 讨论(0)
  • 2020-12-01 05:59

    Swift 3.x

    Accepted answer didn't worked for me too.

    This work for me!

    let url = URL(string: "yourStringUrl")!
    var urlRequest = URLRequest(url: url)
    urlRequest.timeoutInterval = 5 // or what you want
    

    And after:

    Alamofire.request(urlRequest).response(completionHandler: { (response) in
        /// code here
    }
    
    0 讨论(0)
提交回复
热议问题