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?
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
import UIKit
var AFManager = SessionManager()
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let configuration = URLSessionConfiguration.default
configuration.timeoutIntervalForRequest = 5 // seconds
configuration.timeoutIntervalForResource = 5 //seconds
AFManager = Alamofire.SessionManager(configuration: configuration)
return true
}
...
}
Example:
AFManager.request("yourURL", method: .post, parameters: parameters).responseJSON { response in
...
}