-1

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

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

////

}
4

2 回答 2

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)...
于 2019-12-24T04:44:37.797 回答
1

用于timeoutInterval特定 url 或请求的超时。

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(如果提供了)。

于 2019-12-24T05:26:43.317 回答