Setting client-side timeout per request with Alamofire [swift]?
Asked Answered
I

2

10

I'm trying to set a client-side timeout per request for Alamofire for Swift. The lead architect told me to set this on NSURLRequest, but I'm completely confused on how to actually do that in practice.

Can someone who has done this give an example? Thanks!

Inkberry answered 25/11, 2014 at 20:8 Comment(0)
C
17

I think this code may works.

var alamofireManager : Alamofire.Manager?

func some(){
  let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
  configuration.timeoutIntervalForResource = 2 // seconds

  self.alamofireManager = Alamofire.Manager(configuration: configuration)
  self.alamofireManager!.request(.GET, "http://example.com/")
    .response { (request, response, data, error) in

    }
}
Crum answered 2/12, 2014 at 21:14 Comment(2)
Why configuration.timeoutIntervalForResource and not configuration.timeoutIntervalForRequest ?Inkberry
Setting timeoutIntervalForRequest solved my timeout problem. Prior to that, long requests to an API were timing out.Cyclosis
M
0

This is how you can use a per-request timeout using URLRequest:

Alamofire.request(URLRequest(url: ..., cachePolicy: ..., timeoutInterval: 10))
    .response(...)
Mohur answered 12/5, 2017 at 2:22 Comment(1)
While this code snippet may be the solution, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.Flocculant

© 2022 - 2024 — McMap. All rights reserved.