使用Alamofire处理超时

问题描述 投票:34回答:6

是否可以为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 =请求超时。}

swift alamofire
6个回答
79
投票

你可以比较error._code,如果它等于-1001这是NSURLErrorTimedOut然后你知道这是一个超时。

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

21
投票

斯威夫特3

接受的答案对我没有用。

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

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

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

10
投票

Swift 3,Alamofire 4.5.0

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

关键的想法是将Alamofire会话管理器声明为全局变量。然后创建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
    ...
}

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

1
投票

斯威夫特4

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

struct AlamofireManager {
    static let shared: SessionManager = {
        let configuration = URLSessionConfiguration.default
        configuration.timeoutIntervalForRequest = 5
        let sessionManager = Alamofire.SessionManager(configuration: configuration, delegate: SessionDelegate(), serverTrustPolicyManager: nil)
        return sessionManager
    }()
}

class Auth {
    static let api = Auth()

    private init() {}

    func headers() -> HTTPHeaders {
        return [
            "Accept": "XXX",
            "Authorization": "XXX",
            "Content-Type": "XXX"
        ]
    }

    func querySample() {

        AlamofireManager.shared.request("api_post_url", method: .post, parameters: ["parametersKey": "value"], encoding: JSONEncoding.default, headers: headers())
            .responseJSON(queue: DispatchQueue.global(), options: []) { (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() {

        AlamofireManager.shared.request("api_get_url", method: .get, parameters: nil, encoding: JSONEncoding.default, headers: headers())
            .responseJSON(queue: DispatchQueue.global(), options: []) { (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
                }
            }
        })
    }

}
© www.soinside.com 2019 - 2024. All rights reserved.