ios 在 Alamofire 中设置超时

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41803856/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 11:05:39  来源:igfitidea点击:

Set timeout in Alamofire

iosswiftalamofire

提问by ?ernando Valle

I am using Alamofire 4.0.1 and I want to set a timeout for my request. I tried the solutions gived in this question:

我正在使用 Alamofire 4.0.1,我想为我的请求设置超时。我尝试了这个问题中给出的解决方案:

In the first case, it throws a NSURLErrorDomain(timeout is set correctly):

在第一种情况下,它会抛出一个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
                }
            }

In the second case, the time out is not replaced and still set as 60 seconds.

在第二种情况下,超时没有被替换,仍然设置为 60 秒。

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

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

I am running in ios 10.1

我在 ios 10.1 中运行

My code:(it doesn't work)

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

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

Solved Alamofire github thread:Alamofire 4.3.0 setting timeout throws NSURLErrorDomain error #1931

解决了 Alamofire github 线程:Alamofire 4.3.0 设置超时抛出 NSURLErrorDomain 错误 #1931

采纳答案by ?ernando Valle

Based in @kamal-thakur response.

基于@kamal-thakur 的回复。

Swift 3:

斯威夫特3

var request = URLRequest(url: NSURL.init(string: "YOUR_URL") as! URL)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.timeoutInterval = 10 // 10 secs
let postString = "param1=\(var1)&param2=\(var2)"
request.httpBody = postString.data(using: .utf8)
Alamofire.request(request).responseJSON {
    response in
    // do whatever you want here
}

回答by Kamal Thakur

Please Try this:-

请试试这个:-

    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
    }

回答by Aldo Lazuardi

I have same problem too, I think I found the solution. Try to declare SessionManager?or in your case alamofireManagerin class, outside the function

我也有同样的问题,我想我找到了解决方案。尝试在函数之外声明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
       }
     }
   }

}

回答by Istiak Morsalin

Try this:

尝试这个:

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

Swift 3.0

斯威夫特 3.0

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

回答by Letaief Achraf

If you are using one instance of Alamofire, you can make a lazy var like this:

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

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

}()

Works on Swift 4.2

适用于Swift 4.2

回答by Alexander Khitev

As Matt said the problem is the following

正如马特所说,问题如下

The difference here is that the initialized manager is not owned, and is deallocated shortly after it goes out of scope. As a result, any pending tasks are cancelled.

这里的区别在于初始化的管理器不属于自己,并且在它超出范围后不久就会被释放。因此,任何挂起的任务都会被取消。

The solution to this problem was written by rainypixels

这个问题的解决方法是rainypixels写的

import Foundation import Alamofire

进口基金会进口Alamofire

class NetworkManager {

    var manager: Manager?

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

And my own version

还有我自己的版本

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

Can also make a manager for it

也可以为它做一个经理

import Alamofire

struct AlamofireAppManager {

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

}

回答by Jeff Kelley

Alamofire 5.1 includes a new way to modify the request with a closure in the initializer:

Alamofire 5.1 包含一种在初始化程序中使用闭包修改请求的新方法:

AF.request(url) { 
//MARK: - Session Manager
private static var alamofireManager: Session? = {
    let configuration = URLSessionConfiguration.default
    configuration.timeoutIntervalForRequest = 10
    let alamofireManager = Session(configuration: configuration)
    return alamofireManager
}()
.timeoutInterval = 60 } .validate() .response { _ in // handle response here }

回答by Starsky

Based on Letaief Achraf's answer, but for Swift 5.0and Alamofire pod version >= 5.0.0

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

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

        }
    }

Use this variable inside an APIManageror something similar.

在一个APIManager或类似的东西中使用这个变量。

回答by Edgar Estrada

after a lot of try I made it whit the next:

经过多次尝试,我完成了下一个:

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

}

I hope it helps ;)

我希望它有帮助;)

回答by brahimm

None of the above worked for me: Im on swift 4.2Alamofire 4.5

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

I managed to solve it like this :

我设法这样解决它:

##代码##