Handle timeout with Alamofire

匿名 (未验证) 提交于 2019-12-03 01:25:01

问题:

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.}

回答1:

You can compare error.code and if it is equal to -1001 which is NSURLErrorTimedOut then you know this was a timeout.

Swift 3, Alamofire 4.0.1

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:                 //do json stuff                 break             case .failure(let error):                 if error._code == NSURLErrorTimedOut {                     //HANDLE TIMEOUT HERE                 }                 print("\n\nAuth request failed with error:\n \(error)")                 break             }         } 

Swift 2.2

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):             if error._code == NSURLErrorTimedOut {                //HANDLE TIMEOUT HERE             }          print("\n\nAuth request failed with error:\n \(error)")          completion(result: .ConnectionFailed)      } } 


回答2:

Swift 3

Accepted answer didn't worked for me.

After lot of research I did like this.

let manager = Alamofire.SessionManager.default manager.session.configuration.timeoutIntervalForRequest = 120  manager.request("yourUrl", method: .post, parameters: ["parameterKey": "value"]) 


回答3:

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     ... } 


回答4:

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, toUrl urlString: String, completion: @escaping (_ error: Error,_ responseBody: Dictionary?)->()) {         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!")                 }             }         }     } } 


回答5:

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 } 


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!