一尘不染

使用Alamofire处理超时

swift

是否可以为Alamofire请求添加超时处理程序?

在我的项目中,我以这种方式使用Alamofire:

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

编辑:

请求失败消息

错误域= NSURLErrorDomain代码= -1001“请求超时。” UserInfo = {NSUnderlyingError =
0x7fc10b937320 {Error Domain = kCFErrorDomainCFNetwork Code = -1001“(null)”
UserInfo = {_ kCFStreamErrorCodeKey = -2102,_kCFStreamErrorDomainKey =
4}},NSErrorFailingURLStringKey = url,NSErrorFailingURLKey =
URL,_kCFStreamError = -2102 ,NSLocalizedDescription =请求超时。}


阅读 470

收藏
2020-07-07

共1个答案

一尘不染

您可以进行比较error._code,如果等于-1001NSURLErrorTimedOut那么您知道这是超时。

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