Set timeout in Alamofire
Based in @kamal-thakur response.
Swift 3:
var request = URLRequest(url: NSURL.init(string: "YOUR_URL") as! URL)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.timeoutInterval = 10 // 10 secs
let postString = "param1=\(var1)¶m2=\(var2)"
request.httpBody = postString.data(using: .utf8)
Alamofire.request(request).responseJSON {
response in
// do whatever you want here
}
Alamofire set timeout only for specific a request
Try to create a sessionManager for that specific request
let sessionManager: SessionManager = {
var sessionManager = SessionManager()
let configuration = URLSessionConfiguration.default
configuration.timeoutIntervalForRequest = 30 //timeout can be changed from here
sessionManager = Alamofire.SessionManager(configuration: configuration)
return sessionManager
}()
and use this sessionManager
for the call.
sessionManager.request(url, method: .get, parameters: params)...
Handle timeout with Alamofire
You can compare error._code
and if it is equal to -1001
which is NSURLErrorTimedOut
then you know this was a timeout.
let manager = Alamofire.SessionManager.default
manager.session.configuration.timeoutIntervalForRequest = 120
manager.request("yourUrl", method: .post, parameters: ["parameterKey": "value"])
.responseJSON {
response in
switch (response.result) {
case .success: // succes path
case .failure(let error):
if error._code == NSURLErrorTimedOut {
print("Request timeout!")
}
}
}
Related Topics
Detecting If iPhone Is in a Dark Room
How to Keep a Round Imageview Round Using Auto Layout
How to Disable Control Center in iOS 7 Programmatically and If Not, What Are Alternatives
Implement Dark Mode Switch in Swiftui App
The App References Non-Public Selector in Id (Facebook Sdk iOS)
How to Load Resource in Cocoapods Resource_Bundle
Xcode 4/iOS - Send an Email Using Smtp from Inside My App
When to Use Takeunretainedvalue() or Takeretainedvalue() to Retrieve Unmanaged Objects in Swift
Waiting for Multiple Asynchronous Download Tasks
Centering Subview's X in Autolayout Throws "Not Prepared for the Constraint"
Custom Font Not Working Programmatically in Swift
Centering Mkmapview on Spot N-Pixels Below Pin
What Are the Options for Saving Data in iOS
What Describes the Application Delegate Best? How Does It Fit into the Whole Concept
How to Detect Apps First Launch in iOS
How to Call Presentviewcontroller from Within a Uicollectionviewcell