在我们的项目中,我们使用网络管理器来使用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!
}
}
我已经添加了参数timeinterval并在其中设置了默认值。
func sessionManager(timeoutInterval:Double = 30) -> SessionManager {
//passed the param
configuration.timeoutIntervalForRequest = timeoutInterval
}
但是时间间隔值未更新。我的问题是如何使用此功能为每个请求更新SessionManager的超时间隔。我们可以使用每个API的超时间隔来实现它,但我希望它超出常见功能。
您可以将功能重写为:
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呼叫中正常运行
而不是设置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
}