Handle timeout with Alamofire

alamofire timeout not working
the request timed out. swift
alamofire requestretrier
request timeout swift 4
timeout in swift 5
alamofire responsejson
nsurlsession handle timeout
alamofire swiftui

Is it possible to add timeout handler for Alamofire request?

In my project I use Alamofire this way:

init() {
    let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
    configuration.timeoutIntervalForRequest = 30

    self.alamofireManager = Alamofire.Manager(configuration: configuration)
}

func requestAuthorizationWithEmail(email:NSString, password:NSString, completion: (result: RequestResult) -> Void) {

    self.alamofireManager!.request(.POST, "myURL", parameters:["email": email, "password":password])
        .responseJSON { response in
            switch response.result {
            case .Success(let JSON):
                //do json stuff
            case .Failure(let error):
                print("\n\nAuth request failed with error:\n \(error)")
                completion(result: .ConnectionFailed)
            }
    }
}

EDIT:

request fail message

Error Domain=NSURLErrorDomain Code=-1001 "The request timed out." UserInfo={NSUnderlyingError=0x7fc10b937320 {Error Domain=kCFErrorDomainCFNetwork Code=-1001 "(null)" UserInfo={_kCFStreamErrorCodeKey=-2102, _kCFStreamErrorDomainKey=4}}, NSErrorFailingURLStringKey=url, NSErrorFailingURLKey=url, _kCFStreamErrorDomainKey=4, _kCFStreamErrorCodeKey=-2102, NSLocalizedDescription=The request timed out.}

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!")
                }
            }
        }

Alamofire 4.3.0 setting timeout throws NSURLErrorDomain error , I am using the version 4.3.0 of Alamofire and executing on 10.1 . If I build a custom SessionManager for set a timeout, Alamofire throws a  Alamofire.upload: Upload files with multipart, stream, file or data methods. Alamofire.download: Download files or resume a download already in progress. Alamofire.request: Every other HTTP request not associated with file transfers. These Alamofire methods are global within Alamofire so you don’t have to instantiate a class to use them.

Swift 3

The accepted answer didn't work for me.

After a lot of research, I did it like this:

let manager = Alamofire.SessionManager.default
manager.session.configuration.timeoutIntervalForRequest = 120

manager.request("yourUrl", method: .post, parameters: ["parameterKey": "value"])

How to change timeoutIntervalForRequest for Alamofire (5.0.0-beta , change the timeoutIntervalForRequest for alamofire 5 let headers: fractionCompleted)") } // this on is working but with 30 sec timeout interval. Hi @HWSTS,. I'd suggest you open a question on Stack Overflow and tag alamofire.We use our GitHub project for bug reports and feature requests. Best of luck! 🍻

Swift 3, Alamofire 4.5.0

I wanted to set the same timeout for every HTTP call in my project.

The key idea is to declare the Alamofire Session Manager as a global variable. Then to create a URLSessionConfiguration variable, set its timeout in seconds and assign it to the manager.

Every call in the project can use this configured session manager.

In my case the global Alamofire Session Manager variable was set in AppDelegate file (globally) and its configuration was managed in its didFinishLaunchingWithOptions method

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 = 4 // seconds
        configuration.timeoutIntervalForResource = 4 //seconds
        AFManager = Alamofire.SessionManager(configuration: configuration)

        return true
    }
    ...
}

From now the Alamofire request function can be called from any part of the app using the afManager.

For example:

AFManager.request("yourURL", method: .post, parameters: parameters, encoding: JSONEncoding.default).validate().responseJSON { response in
    ...
}

Handle timeout with Alamofire, Is it possible to add timeout handler for Alamofire request? In my project I use Alamofire this way: init() { let configuration  In order to keep Alamofire focused specifically on core networking implementations, additional component libraries have been created by the Alamofire Software Foundation to bring additional functionality to the Alamofire ecosystem. The Swift Package Manager is a tool for automating the distribution

Swift 3.x

class NetworkHelper {
    static let shared = NetworkHelper()
    var manager: SessionManager {
        let manager = Alamofire.SessionManager.default
        manager.session.configuration.timeoutIntervalForRequest = 10
        return manager
    }
    func postJSONData( withParams parameters: Dictionary<String, Any>, toUrl urlString: String, completion: @escaping (_ error: Error,_ responseBody: Dictionary<String, AnyObject>?)->()) {
        manager.request(urlString, method: .post, parameters: parameters, encoding: JSONEncoding.default).responseJSON { response in 
            if let error = response.result.error {
                if error._code == NSURLErrorTimedOut {
                    print("Time out occurs!")
                }
            }
        }
    }
}

Handle timeout with Alamofire, Handle timeout with Alamofire. alamofire timeout not working request timeout swift 4 alamofire responsejson alamofire swiftui timeout in swift 5 alamofire post I am using the version 4.3.0 of Alamofire and executing on 10.1 . If I build a custom SessionManager for set a timeout, Alamofire throws a NSURLErrorDomain I asked in StackOverflow but every solution does not work. import Foundation impo

Swift 3.x

Accepted answer didn't worked for me too.

This work for me!

let url = URL(string: "yourStringUrl")!
var urlRequest = URLRequest(url: url)
urlRequest.timeoutInterval = 5 // or what you want

And after:

Alamofire.request(urlRequest).response(completionHandler: { (response) in
    /// code here
}

timeoutIntervalForRequest, timeoutIntervalForRequest. The timeout interval to use when waiting for additional data. SDKs. iOS  OkHttpClient.Builder API provides 4 methods which can be used to set timeouts. callTimeout (Duration duration) – Sets the default timeout for complete calls. The call timeout spans the entire call: resolving DNS, connecting, writing the request body, server processing, and reading the response body.

Alamofire Tutorial: Getting Started, Take your first steps into Alamofire, the de facto networking library on In addition, there are numerous third party libraries that help with handling JSON. reloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 10.0  Completion Handlers in Swift November 16, 2015 - Updated: November 10, 2016 - Swift 3.0 We’ve been making lots of API calls using Alamofire and dataTask(with request:) , like in Simple REST API Calls with Swift .

swift Handle timeout with Alamofire?, let manager = Alamofire.SessionManager.default manager.session.configuration.​timeoutIntervalForRequest = 120 manager.request("yourUrl", method: .post,  To integrate AlamofireImage into your Xcode project using Carthage, specify it in your Cartfile: github "Alamofire/AlamofireImage" ~> 4.1 Swift Package Manager. The Swift Package Manager is a tool for automating the distribution of Swift code and is integrated into the swift compiler. It is in early development, but AlamofireImage does support

Authentication with signed requests in Alamofire 5, Combining a RequestAdapter with a RequestRetrier for handling authenticated requests. While building your authentication layer for network  Both iOS’s Alamofire and Android’s OkHttp uses a third-party tool to handle the JSON payload. This make sense, as the payload could be in other formats (e.g. Protobuf).

Comments
  • Doesn't the timeout also trigger the .Failure? Never tested it with Alamofire, but most other systems I use fallback to the error/failure like that. What have you tested?
  • @Allendar you're right, my fault that i have not mentioned that. I've edited my question.
  • The response object will contain the HTTP status. If it is 408 (408 Request Timeout), then you can check that inside the .Failure call and handle it appropriately. There are probably even macros for the http-statuses so you can simply check something like HTTP_STATUS_408 as an integer placeholder.
  • This is true, but not promoted to do so, because if you work in teams these weird checks on exact "under-water" codes will make code very unreadable. Nonetheless a correct answer tho, so +1.
  • Totally agree with you, I've made some update and make this snippet more human readable :)
  • I've made some research and we can use NSURLErrorTimedOut from NSURLError class.
  • I use this snippet to handle timeout error. My platform is Xcode 8, Swift 3. the enum result value seems to be .success and .failure instead of .Success and .Failure.
  • can anyone tell me how does one know to use error._code? This does not seem to appear in any documentation
  • can u provide code for newest version of alamofire? TKs
  • this throws Error Domain=NSURLErrorDomain Code=-999 "cancelled"
  • @brahimm pls try to improve the thread queue use the DispatchQueue.global() as my update
  • can you tell me why specifying the background thread there solves this problem !
  • I think this error due to multiple request to query on serial queue at same time. improved the DispatchQueue.global() to concurrent queue.
  • the problem is still there