I am using Alamofire 4.0.1 and I want to set a timeout for my request. I tried the solutions gived in this question:
In the first case
As Matt said the problem is the following
The difference here is that the initialized manager is not owned, and is deallocated shortly after it goes out of scope. As a result, any pending tasks are cancelled.
The solution to this problem was written by rainypixels
import Foundation import Alamofire
class NetworkManager {
var manager: Manager?
init() {
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
manager = Alamofire.Manager(configuration: configuration)
}
}
And my own version
class APIManager {
private var sessionManager = Alamofire.SessionManager()
func requestCards(_ days_range: Int, success: ((_ cards: [CardModel]) -> Void)?, fail: ((_ error: Error) -> Void)?) {
DispatchQueue.global(qos: .background).async {
let parameters = ["example" : 1]
let headers = ["AUTH" : "Example"]
let configuration = URLSessionConfiguration.default
configuration.timeoutIntervalForRequest = 10
self.sessionManager = Alamofire.SessionManager(configuration: configuration)
self.sessionManager.request(URLs.cards.value, method: .get, parameters: parameters, encoding: URLEncoding.default, headers: headers).responseJSON { (response) in
switch response.result {
case .success:
//do json stuff
guard let json = response.result.value as? [String : Any] else { return }
guard let result = json["result"] as? [[String : Any]] else { return }
let cards = Mapper().mapArray(JSONArray: result)
debugPrint("cards", cards.count)
success?(cards)
case .failure(let error):
if error._code == NSURLErrorTimedOut {
//timeout here
debugPrint("timeOut")
}
debugPrint("\n\ncard request failed with error:\n \(error)")
fail?(error)
}
}
}
}
}
Can also make a manager for it
import Alamofire
struct AlamofireAppManager {
static let shared: SessionManager = {
let configuration = URLSessionConfiguration.default
configuration.timeoutIntervalForRequest = 10
let sessionManager = Alamofire.SessionManager(configuration: configuration)
return sessionManager
}()
}