在Alamofire设置超时

时间:2017-01-23 10:15:18

标签: ios swift alamofire

我正在使用Alamofire 4.0.1和我想为我的请求设置超时。我尝试了这个question中提供的解决方案:

在第一种情况中,它会抛出 NSURLErrorDomain (超时设置正确):

let configuration = URLSessionConfiguration.default
configuration.timeoutIntervalForRequest = 10

    let sessionManager = Alamofire.SessionManager(configuration: configuration)
    sessionManager.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 {
                        //timeout here
                    }
                    print("\n\nAuth request failed with error:\n \(error)")
                    break
                }
            }

在第二种情况中,超时未被替换,仍设为60秒。

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

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

我在ios 10.1中运行

我的代码:(它不起作用)

    let configuration = URLSessionConfiguration.default
    configuration.timeoutIntervalForRequest = 10 // seconds
    configuration.timeoutIntervalForResource = 10
    let alamoFireManager = Alamofire.SessionManager(configuration: configuration)

    alamoFireManager.request("my_url", method: .post, parameters: parameters).responseJSON { response in


        switch (response.result) {
        case .success:
                 //Success....
            break
        case .failure(let error):
            // failure...
            break
        }
    }

解决了Alamofire github主题: Alamofire 4.3.0 setting timeout throws NSURLErrorDomain error #1931

14 个答案:

答案 0 :(得分:24)

请试试这个: -

    let request = NSMutableURLRequest(url: URL(string: "")!)
    request.httpMethod = "POST"
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    request.timeoutInterval = 10 // 10 secs
    let values = ["key": "value"]
    request.httpBody = try! JSONSerialization.data(withJSONObject: values, options: [])
    Alamofire.request(request as! URLRequestConvertible).responseJSON {
        response in
        // do whatever you want here
    }

答案 1 :(得分:17)

我也有同样的问题,我想我找到了解决方案。尝试在函数

之外的类中声明SessionManager?或您的alamofireManager
class ViewController: UIViewController {
   var alamoFireManager : SessionManager? // this line

   func alamofire(){
        let configuration = URLSessionConfiguration.default
        configuration.timeoutIntervalForRequest = 10
        configuration.timeoutIntervalForResource = 10
        alamoFireManager = Alamofire.SessionManager(configuration: configuration) // not in this line

        alamoFireManager.request("my_url", method: .post, parameters: parameters).responseJSON { response in


        switch (response.result) {
        case .success:
                 //Success....
            break
        case .failure(let error):
               // failure...
             break
       }
     }
   }

}

答案 2 :(得分:11)

试试这个:

    let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
    configuration.timeoutIntervalForRequest = 4 // seconds
    configuration.timeoutIntervalForResource = 4
    self.alamoFireManager = Alamofire.Manager(configuration: configuration)

Swift 3.0

    let configuration = URLSessionConfiguration.default
    configuration.timeoutIntervalForRequest = 4 // seconds
    configuration.timeoutIntervalForResource = 4
    self.alamoFireManager = Alamofire.SessionManager(configuration: configuration)

答案 3 :(得分:9)

Alamofire 5.1包含一种通过初始化程序中的关闭符修改请求的新方法:

AF.request(url) { $0.timeoutInterval = 60 }
    .validate()
    .response { _ in // handle response here }

答案 4 :(得分:8)

Matt说问题如下

  

这里的不同之处在于初始化的管理器不是拥有的,并且在它超出范围后不久就会被释放。因此,任何待处理的任务都将被取消。

此问题的解决方案由rainypixels编写

导入基金会 进口Alamofire

class NetworkManager {

    var manager: Manager?

    init() {
        let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
        manager = Alamofire.Manager(configuration: configuration)
    }
}

我自己的版本

class APIManager {

    private var sessionManager = Alamofire.SessionManager()

    func requestCards(_ days_range: Int, success: ((_ cards: [CardModel]) -> Void)?, fail: ((_ error: Error) -> Void)?) {
        DispatchQueue.global(qos: .background).async {
            let parameters = ["example" : 1]

            let headers = ["AUTH" : "Example"]

            let configuration = URLSessionConfiguration.default
            configuration.timeoutIntervalForRequest = 10
            self.sessionManager = Alamofire.SessionManager(configuration: configuration)

            self.sessionManager.request(URLs.cards.value, method: .get, parameters: parameters, encoding: URLEncoding.default, headers: headers).responseJSON { (response) in
                switch response.result {
                case .success:
                    //do json stuff
                    guard let json = response.result.value as? [String : Any] else { return }
                    guard let result = json["result"] as? [[String : Any]] else { return }
                    let cards = Mapper<CardModel>().mapArray(JSONArray: result)
                    debugPrint("cards", cards.count)
                    success?(cards)
                case .failure(let error):
                    if error._code == NSURLErrorTimedOut {
                        //timeout here
                        debugPrint("timeOut")
                    }
                    debugPrint("\n\ncard request failed with error:\n \(error)")
                    fail?(error)
                }
            }
        }
    }
}

也可以为它做一个经理

import Alamofire

struct AlamofireAppManager {

    static let shared: SessionManager = {
        let configuration = URLSessionConfiguration.default
        configuration.timeoutIntervalForRequest = 10
        let sessionManager = Alamofire.SessionManager(configuration: configuration)
        return sessionManager
    }()

}

答案 5 :(得分:6)

基于@ kamal-thakur回复。

Swift 3

{{1}}

答案 6 :(得分:6)

基于Letaief Achraf的回答,但针对 Swift 5.0 Alamofire pod version >= 5.0.0

//MARK: - Session Manager
private static var alamofireManager: Session? = {
    let configuration = URLSessionConfiguration.default
    configuration.timeoutIntervalForRequest = 10
    let alamofireManager = Session(configuration: configuration)
    return alamofireManager
}()

APIManager或类似名称中使用此变量。

答案 7 :(得分:2)

经过大量尝试后,我在下一场比赛中表现出色:

var timeout = 300 // 5 minutes

//Post values
    let parameters:Parameters = parameters

    //Server value
    let url:URL = (url)


    //Make the request
    let configuration = URLSessionConfiguration.default
    configuration.timeoutIntervalForResource = TimeInterval(timeout)
    configuration.timeoutIntervalForRequest = TimeInterval(timeout)

    let sessionManager = Alamofire.SessionManager(configuration: configuration)

     sessionManager.request(url,parameters:parameters).validate(statusCode: 200..<300).responseJSON { response in


        print(response.request)  // original URL request
        print(response.response) // URL response

        print(sessionManager.session.configuration.timeoutIntervalForRequest)   // result of response time
        print(response.timeline.totalDuration)


        switch response.result {
        case .success:

            if let valJSON = response.result.value {


               //use your json result 



            }

        case .failure (let error):

            print("\n\nAuth request failed with error:\n \(error)")

        }
    }

我希望它有所帮助;)

答案 8 :(得分:2)

如果您使用的是Alamofire实例,则可以像这样创建一个惰性变量:

   private lazy var alamoFireManager: SessionManager? = {
    let configuration = URLSessionConfiguration.default
    configuration.timeoutIntervalForRequest = 5
    configuration.timeoutIntervalForResource = 5
    let alamoFireManager = Alamofire.SessionManager(configuration: configuration)
    return alamoFireManager

}()

Swift 4.2

上运行

答案 9 :(得分:2)

在Swift 5中,您可以通过这种方式完成。

AF.sessionConfiguration.timeoutIntervalForRequest = 60

答案 10 :(得分:0)

我有swift的代码2.3希望它可以帮到你,试试吧

    let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
    configuration.timeoutIntervalForResource = 10800 // seconds
    configuration.timeoutIntervalForRequest = 10800 // seconds

    alamoFireManager = Alamofire.Manager(configuration: configuration)

答案 11 :(得分:0)

对我有用:

let url:String = "http://..."
let request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("Kirk Hamet", forHTTPHeaderField:"name")
request.timeoutInterval = 23 //Second

Alamofire.request(request).responseJSON {
                response in
    if response.result.isSuccess == true {

    }else{

    }

}

Swift 4.1

答案 12 :(得分:0)

如果您不想自己构建一个UrlRequest,仍然可以使用Alamofire来构建它。

    // set this flag to false so the request will not be sent until
    // resume() is called
    sessionManager.startRequestsImmediately = false

    var urlRequest = sessionManager.request(url,
                                            method: method,
                                            parameters: params,
                                            encoding: encoding,
                                            headers: allHeaders).request!

    urlRequest.timeoutInterval = 10

    let request = sessionManager.request(urlRequest).responseJSON { (result) in
        // use the result
    }

    // need to start the request
    request.resume()

答案 13 :(得分:-1)

以上都不适合我:我在swift 4.2 Alamofire 4.5

我设法解决了这个问题:

let request = Alamofire.request("routee", method: .post, parameters: data, encoding: JSONEncoding.default, headers: getHeaders())

/// getting request created by Alamofire and then updating its timeout Value

let url = URL(string: "myroute")!
        var request = try URLRequest(url: url, method: method, headers: headers)
        request.timeoutInterval = 900 // timeout
        request = try JSONEncoding.default.encode(request, with: data)

Alamofire.request(request)
    .responseJSON { response in

}