首页 文章

使用Alamofire处理超时

提问于
浏览
28

是否可以为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,_kCFStreamErrorDomainKey = 4,_kCFStreamErrorCodeKey = -2102 ,NSLocalizedDescription =请求超时 . }

6 回答

  • 0

    您可以比较 error.code ,如果它等于 -1001 ,即 NSURLErrorTimedOut ,那么您知道这是一个超时 .

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

    斯威夫特3

    接受的答案对我没用 .

    经过大量的研究,我确实喜欢这个 .

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

    Swift 3,Alamofire 4.5.0

    我想为项目中的每个HTTP调用设置相同的超时 .

    关键的想法是声明Alamofire会话管理器 as a global variable . 然后创建URLSessionConfiguration变量,以秒为单位设置其超时并将其分配给管理器 .

    项目中的每个调用都可以使用此配置的会话管理器 .

    在我的例子中,全局Alamofire会话管理器变量在AppDelegate文件中设置(全局),其配置在其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
        }
        ...
    }
    

    从现在开始,可以使用afManager从应用程序的任何部分调用Alamofire请求函数 .

    例如:

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

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

    Swift 3.x

    接受的答案对我也没有用 .

    这项工作对我来说!

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

    之后:

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

    Swift 4

    我的方式和超时功能是可行的,同时为api类练习单例 . 参考来自here

    class Auth {
        static let api = Auth()
        private var alamoFire: SessionManager?
    
        private init() {}
    
        func headers() -> HTTPHeaders {
            return [
                "Accept": "XXX",
                "Authorization": "XXX",
                "Content-Type": "XXX"
            ]
        }
    
        func alamofireConfig(timeout lhs: TimeInterval) {
            let configuration = URLSessionConfiguration.default
            configuration.timeoutIntervalForRequest = lhs
            configuration.timeoutIntervalForResource = lhs
            alamoFire = Alamofire.SessionManager(configuration: configuration, delegate: SessionDelegate(), serverTrustPolicyManager: nil)
        }
    
        func querySample() {
    
            alamofireConfig(timeout: 10)
            alamoFire?.request("api_post_url", method: .post, parameters: ["parametersKey": "value"], encoding: JSONEncoding.default, headers: headers())
                .responseJSON(completionHandler: { (response) in
                switch response.result {
                case .success(let value):
                    // do your statement
                case .failure(let error):
                    if error._code == NSURLErrorTimedOut {
                        // timeout error statement
                    } else {
                        // other error statement
                    }
                }
            })
        }
    
        func queryOtherSample() {
    
            alamofireConfig(timeout: 5)
            alamoFire?.request("api_get_url", method: .get, parameters: nil, encoding: JSONEncoding.default, headers: headers())
                .responseJSON(completionHandler: { (response) in
                switch response.result {
                case .success(let value):
                    // do your statement
                case .failure(let error):
                    if error._code == NSURLErrorTimedOut {
                        // timeout error statement
                    } else {
                        // other error statement
                    }
                }
            })
        }
    
    }
    

相关问题