swift 2.1 alamofire timeout method

2019-04-29 04:25发布

i have question about alamofire timeout methods, first of all , my english may not be good enough to let you guys to understand what i said... but i will tired to explain my question

in my project, i used alamofire , for some reason , i need to make sure my app working of poor connection area. so i am thinking using timeout method.

i saw there are some people said , use Solution 1:

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

will solved the problem, but in my case , i saw the debug area said my request is "cancel"

so i tried another solution which i saw on here(stackoverflow) Solution 2:

let manager = Alamofire.Manager.sharedInstance
    manager.session.configuration.timeoutIntervalForRequest = 5
    manager.request(.POST, url, parameters: params, encoding: .JSON, headers: nil).response(queue: dispatch_get_main_queue()) { (Request, res, data, error) -> Void in{}

this method seems should be working , but only if i let my app went to background and reactive my app ,the debug area show request "timeout", otherwise the debug area didnt show anything ,unless i switch it to background and reactive the app.

I'm using Xcode 7.1 and ios 9.0

UPDATE: if i used Solution 2 , if i let the requesttimeout = 5 , the debug area will show the "timeout error", but it take more than 5 sec... sometimes it will show around 30s, but sometimes more than 1 min....

UPDATE2 : i found out what the problem is. the problem is if you are using reachabilty framework to detect connect status, then the system might detect the connect is on or not first , then it will show the request timeout after the isReachable( it may take up to 1 min).

1条回答
看我几分像从前
2楼-- · 2019-04-29 04:58

Based on NSURLSessionConfiguration Class Reference

This property determines the request timeout interval for all tasks within sessions based on this configuration. The request timeout interval controls how long (in seconds) a task should wait for additional data to arrive before giving up. The timer associated with this value is reset whenever new data arrives. When the request timer reaches the specified interval without receiving any new data, it triggers a timeout.

Timer is reset whenever new data arrives and that is why you have different error time.

Also you could set one more parameter for the request :

manager.session.configuration.timeoutIntervalForResource = 5
查看更多
登录 后发表回答