【问题标题】:Updated the almofire timeoutIntervalForRequest for each API in swift?快速更新了每个 API 的 almofire timeoutIntervalForRequest?
【发布时间】:2020-02-11 07:54:09
【问题描述】:

在我们的项目中,我们使用网络管理器来处理所有使用 Alamofire 的请求和响应。在 alamofire 中,我们将默认的内部超时设置为 30。但是我们需要将某些请求的“timeoutIntervalForRequest”更改为 50,60 等。

private var manager : SessionManager?

    func sessionManager() -> SessionManager {
        if let manage = self.manager {
            return manage
        }
        else {
            let configuration = URLSessionConfiguration.default
            configuration.timeoutIntervalForRequest = 30
            self.manager = SessionManager(configuration: configuration, delegate: CustomSessionDelegate())
            return self.manager!
        }
    }

我已经添加了参数时间间隔并在其中设置了默认值。

func sessionManager(timeoutInterval:Double = 30) -> SessionManager {
//passed the param 
configuration.timeoutIntervalForRequest = timeoutInterval
}

但是时间间隔值没有更新。我的问题是如何使用此函数为每个请求更新 SessionManager 的超时间隔。我们可以使用每个 API 的超时间隔来实现它,但我希望它高于通用功能。

【问题讨论】:

    标签: ios swift networking alamofire


    【解决方案1】:

    您可以将函数重写为:

    func sessionManager(timeInterval : Double) -> SessionManager {
            if let manage = self.manager {
                return manage
            }
            else {
                let configuration = URLSessionConfiguration.default
                configuration.timeoutIntervalForRequest = timeInterval
                self.manager = SessionManager(configuration: configuration, delegate: CustomSessionDelegate())
                return self.manager!
            }
        }
    

    在每次 Api 调用中都能正常工作

    【讨论】:

    • 1.我们在第一个 API 中将 timeoutIntervalForRequest 设置为 30,在第二个 API 中,调用 if let 块并采用超时 30 管理。
    • 通过这种方法,您可以为所有 api 调用设置自定义时间间隔
    • 是的,但是当我尝试设置自定义时间间隔时。如果让 manage = self.manager 块被调用。
    【解决方案2】:

    与其设置 timeoutIntervalForRequest,不如在 URLRequest 对象中设置 timeoutInterval,然后将该请求传递给 Alamofire 函数。

        let request = NSMutableURLRequest(url: URL(string: "")!)
            request.httpMethod = "POST"
            request.setValue("application/json", forHTTPHeaderField: "Content-Type")
            request.timeoutInterval = 50 
    Alamofire.request(request as! URLRequestConvertible).responseJSON {
            response in
            // do whatever you want here
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-29
      • 2015-01-24
      • 1970-01-01
      • 1970-01-01
      • 2020-02-17
      • 1970-01-01
      • 1970-01-01
      • 2015-11-01
      相关资源
      最近更新 更多