-1

I'm sending requests using Alamofire as below. I need to know how can I set the timeout only for a specific request like this

Alamofire.request(URL, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers).validate().responseJSON { (response) in switch response.result {

////

}
hashB
  • 113
  • 1
  • 12
  • 1
    Does this answer your question? [Set timeout in Alamofire](https://stackoverflow.com/questions/41803856/set-timeout-in-alamofire) – Malik Dec 24 '19 at 04:49
  • Possible duplicate of https://stackoverflow.com/questions/36626075/handle-timeout-with-alamofire – Malik Dec 24 '19 at 04:52

2 Answers2

2

Try to create a sessionManager for that specific request

let sessionManager: SessionManager = {
    var sessionManager = SessionManager()
    let configuration = URLSessionConfiguration.default
    configuration.timeoutIntervalForRequest = 30  //timeout can be changed from here
    sessionManager = Alamofire.SessionManager(configuration: configuration)
    return sessionManager
}()

and use this sessionManager for the call.

sessionManager.request(url, method: .get, parameters: params)...
Aditya
  • 783
  • 1
  • 8
  • 25
  • The problem: It's will apply for all request. – Duy Phan Dec 24 '19 at 04:49
  • @DuyPhan No. It will only apply the configuration to requests that use `sessionManager.request`. Other requests can still use `Alamofire.request` – Malik Dec 24 '19 at 04:50
1

for timeout use timeoutInterval for a specific url or request.

if let url = NSURL.init(string: "YOUR_URL") {
        var request = URLRequest(url: url as URL)
        request.httpMethod = "POST"
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")

        if let myUrl = NSURL.init(string: "SPECIFIC_URL"),
            myUrl.isEqual(url) {
            request.timeoutInterval = 10 // 10 secs
        }

        let postString = "param1=\(var1)&param2=\(var2)"
        request.httpBody = postString.data(using: .utf8)
        Alamofire.request(request).responseJSON { response in
            ///  handle response here
        }
    }

according to git hub validate() checks for the status codes are within the 200..<300 range, and that the Content-Type header of the response matches the Accept header of the request, if one is provided.

Shabbir
  • 289
  • 2
  • 6