ios NSURLSession:如何增加 URL 请求的超时时间?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23428793/
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 00:04:04  来源:igfitidea点击:

NSURLSession: How to increase time out for URL requests?

iosobjective-cswifthttpnsurlconnection

提问by AlexR

I am using iOS 7's new NSURLSessionDataTaskto retrieve data as follows:

我正在使用 iOS 7 的 newNSURLSessionDataTask来检索数据,如下所示:

NSURLSession *session = [NSURLSession sharedSession];

NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:
request completionHandler:
^(NSData *data, NSURLResponse *response, NSError *error) {
//
}];

How can I increase the time out values to avoid the error "The request timed out"(in NSURLErrorDomainCode=-1001)?

如何增加超时值以避免错误"The request timed out"(在 NSURLErrorDomainCode= 中-1001)?

I have checked the documentation for NSURLSessionConfigurationbut did not find a way to set the time out value.

我已经检查了NSURLSessionConfiguration的文档,但没有找到设置超时值的方法。

Thank you for your help!

感谢您的帮助!

回答by RaffAl

ObjC

对象

NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
sessionConfig.timeoutIntervalForRequest = 30.0;
sessionConfig.timeoutIntervalForResource = 60.0;

Swift

迅速

let sessionConfig = URLSessionConfiguration.default
sessionConfig.timeoutIntervalForRequest = 30.0
sessionConfig.timeoutIntervalForResource = 60.0
let session = URLSession(configuration: sessionConfig)

What docs say

什么文档说

timeoutIntervalForRequestand timeoutIntervalForResourcespecify the timeout interval for the request as well as the resource.

timeoutIntervalForRequesttimeoutIntervalForResource指定请求和资源的超时间隔。

timeoutIntervalForRequest- The timeout interval to use when waiting for additional data. The timer associated with this value is reset whenever new data arrives. When the request timer reaches the specified interval without receiving any new data, it triggers a timeout.

timeoutIntervalForResource- The maximum amount of time that a resource request should be allowed to take. This value controls how long to wait for an entire resource to transfer before giving up. The resource timer starts when the request is initiated and counts until either the request completes or this timeout interval is reached, whichever comes first.

timeoutIntervalForRequest- 等待额外数据时使用的超时间隔。每当新数据到达时,与此值关联的计时器就会重置。当请求定时器到达指定的时间间隔而没有接收到任何新数据时,就会触发超时。

timeoutIntervalForResource- 应允许资源请求占用的最长时间。此值控制在放弃之前等待整个资源传输的时间。资源计时器在请求发起时启动并计数,直到请求完成或达到此超时间隔(以先到者为准)。

Based on NSURLSessionConfiguration Class Reference

基于NSURLSessionConfiguration 类参考

回答by Sruit A.Suk

In case Swift developer coming here

如果 Swift 开发人员来到这里

to do this, you need to use

为此,您需要使用

    let urlconfig = NSURLSessionConfiguration.defaultSessionConfiguration()
    urlconfig.timeoutIntervalForRequest = 12
    urlconfig.timeoutIntervalForResource = 12
    self.session = NSURLSession(configuration: urlconfig, delegate: self.delegates, delegateQueue: nil)

回答by Danil Shaykhutdinov

In swift 3. timeout 15 seconds.

在 swift 3. 超时 15 秒。

    let configuration = URLSessionConfiguration.default
    configuration.timeoutIntervalForRequest = TimeInterval(15)
    configuration.timeoutIntervalForResource = TimeInterval(15)
    let session = URLSession(configuration: configuration)

回答by Wojtek Surowka

NSURLSessionConfiguration includes the property timeoutIntervalForRequest:

NSURLSessionConfiguration 包括属性 timeoutIntervalForRequest:

@property NSTimeInterval timeoutIntervalForRequest

to control the timeout interval. There is also timeoutIntervalForResource for the timeout after the request is initiated.

来控制超时间隔。还有 timeoutIntervalForResource 用于请求发起后的超时。

回答by Lineesh K Mohan

In SWIFT 3.0, You need to use

在 SWIFT 3.0 中,您需要使用

 if let cleanURLString = urlString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed),
    let theURL: Foundation.URL = Foundation.URL(string: cleanURLString) {

    var task:URLSessionDataTask?
    let urlconfig = URLSessionConfiguration.default
    urlconfig.timeoutIntervalForRequest = 20
    urlconfig.timeoutIntervalForResource = 60
    let session = Foundation.URLSession(configuration: urlconfig, delegate: self, delegateQueue: OperationQueue.main)

    let request = URLRequest(url: theURL)
    request.httpMethod = "POST"
    request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringCacheData
    request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
    let paramString = YourParameterString
    request.httpBody = paramString.data(using: String.Encoding.utf8)

    task = session.dataTask(with: request) {
        (data, response, error) in
        // Do here
    })
    dataTask.resume()
}

回答by Nico Dioso

In my case I was increasing the timeout of the wrong class. My timeout error was solved by increasing the timeout of the URLRequestnot the URLSession

就我而言,我增加了错误课程的超时时间。我的超时错误是通过增加URLRequest的超时而不是URLSession 来解决的

var request = URLRequest(url: url)
request.timeoutInterval = 30

回答by Nico Dioso

For Swift 4:

对于 Swift 4:

let config = URLSessionConfiguration.default
config.timeoutIntervalForRequest = TimeInterval(15)
config.timeoutIntervalForResource = TimeInterval(15)
let urlSession = URLSession(configuration: config)

The timeoutIntervalForRequest is for all tasks within sessions based on this configuration. The timeoutIntervalForResource is for all tasks within sessions based on this configuration.

timeoutIntervalForRequest 适用于基于此配置的会话中的所有任务。timeoutIntervalForResource 适用于基于此配置的会话中的所有任务。