I am using Alamofire for network request and want to add timeout. But Alamofire's function is not working. Nothing happens when I write the following code
let manager = Alamofire.SessionManager.default
manager.session.configuration.timeoutIntervalForRequest = 1 // not working, 20 secs normally (1 just for try)
manager.request(url, method: method, parameters: params)
.responseJSON { response in
print(response)
...
When I try without Alamofire for network request, timeout working successfully. But there are other mistakes.
var request = URLRequest(url: URL(string: url)!)
request.httpMethod = "post"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.timeoutInterval = 1 // 20 secs normally (1 just for try)
request.httpBody = try! JSONSerialization.data(withJSONObject: params!)
...
So, how can i add timeout for Alamofire in Swift 3?
You can't modify the values of a
URLSessionConfiguration
after it has be added to aURLSession
, so attempting to manipulateAlamofire.SesssionManager.default.session.configuration
will always fail. To properly change the configuration values, follow the Alamofire documentation for instantiating your ownSessionManager
. For example:Finally I found a solution to this answer: https://stackoverflow.com/a/44948686/7825024
This configuration code does not work when I add my function, but it works when I add it to AppDelegate!
AppDelegate.swift
Example: