Manejar el tiempo de espera con Alamofire
¿Es posible agregar el controlador de tiempo de espera para la solicitud Alamofire?
En mi proyecto uso Alamofire de esta manera:
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)
}
}
}
EDITAR:
Mensaje de error de solicitud
Error Domain=NSURLErrorDomain Code=-1001 "Se agotó el tiempo de espera de la solicitud."userInfo = {NSUnderlyingError = 0x7fc10b937320 {Error Domain = kCFErrorDomainCFNetwork Code=-1001" (null) " userInfo = {_kCFStreamErrorCodeKey = -2102, _kCFStreamErrorDomainKey = 4}}, NSErrorFailingURLStringKey = url, NSErrorFailingURLKey = url, _kCFStreamErrorDomainKey = 4, _kCFStreamErrorCodeKey=-2102, NSLocalizedDescription = El tiempo de espera de la solicitud ha expirado.}
5 answers
Puedes comparar error.code
y si es igual a -1001
que es NSURLErrorTimedOut
entonces sabes que esto fue un tiempo de espera.
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)
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-25 08:17:29
Swift 3
Respuesta aceptada no funcionó para mí.
Después de mucha investigación me gustó esto.
let manager = Alamofire.SessionManager.default
manager.session.configuration.timeoutIntervalForRequest = 120
manager.request("yourUrl", method: .post, parameters: ["parameterKey": "value"])
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-20 13:37:17
Swift 3, Alamofire 4.5.0
Quería establecer el mismo timeout para cada llamada HTTP en mi proyecto.
La idea clave es declarar el Gestor de sesiones de Alamofire como variable global . Luego, para crear una variable URLSessionConfiguration, establezca su tiempo de espera en segundos y asígnela al administrador.
Cada llamada en el proyecto puede usar este administrador de sesión configurado .
En mi caso la Sesión global Alamofire La variable Manager se estableció en el archivo AppDelegate (globalmente) y su configuración se gestionó en su método didFinishLaunchingWithOptions
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
}
...
}
A partir de ahora, la función Alamofire request se puede llamar desde cualquier parte de la aplicación utilizando el afManager.
Por ejemplo:
AFManager.request("yourURL", method: .post, parameters: parameters, encoding: JSONEncoding.default).validate().responseJSON { response in
...
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-06 12:18:47
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!")
}
}
}
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-10-10 11:12:10
Swift 3.x
Respuesta aceptada no funcionó para mí también.
Este trabajo para mí!
let url = URL(string: "yourStringUrl")!
var urlRequest = URLRequest(url: url)
urlRequest.timeoutInterval = 5 // or what you want
Y después:
Alamofire.request(urlRequest).response(completionHandler: { (response) in
/// code here
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-19 18:09:20