Alamofire仅针对特定请求设置超时

时间:2019-12-24 04:36:03

标签: ios swift alamofire alamofire-request

我正在使用Alamofire发送请求,如下所示。我需要知道如何仅为这样的特定请求设置超时时间

Alamofire.request(URL, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers).validate().responseJSON { (response) in switch response.result {

////

}

2 个答案:

答案 0 :(得分:2)

尝试为该特定请求创建sessionManager

let sessionManager: SessionManager = {
    var sessionManager = SessionManager()
    let configuration = URLSessionConfiguration.default
    configuration.timeoutIntervalForRequest = 30  //timeout can be changed from here
    sessionManager = Alamofire.SessionManager(configuration: configuration)
    return sessionManager
}()

并使用此sessionManager进行通话。

sessionManager.request(url, method: .get, parameters: params)...

答案 1 :(得分:0)

对于超时,请对特定的网址或请求使用timeoutInterval

if let url = NSURL.init(string: "YOUR_URL") {
        var request = URLRequest(url: url as URL)
        request.httpMethod = "POST"
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")

        if let myUrl = NSURL.init(string: "SPECIFIC_URL"),
            myUrl.isEqual(url) {
            request.timeoutInterval = 10 // 10 secs
        }

        let postString = "param1=\(var1)&param2=\(var2)"
        request.httpBody = postString.data(using: .utf8)
        Alamofire.request(request).responseJSON { response in
            ///  handle response here
        }
    }

根据git hub validate()检查状态码是否在200..<300范围内,并且响应的Content-Type标头与广告代码的Accept标头匹配请求,如果提供了一个。