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

标签 ios objective-c swift http nsurlsession

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

NSURLSession *session = [NSURLSession sharedSession];

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

如何增加超时值以避免错误“请求超时”(在NSURLErrorDomain Code=-1001中) ?

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

感谢您的帮助!

最佳答案

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)

文档怎么说

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.

基于 NSURLSessionConfiguration Class Reference

关于ios - NSURLSession:如何增加 URL 请求的超时时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23428793/

相关文章:

ios - 将文件上传到 s3,然后将 URL 存储在 Firebase 中 - Swift 2.2

ios - 在 SWRevealViewController 中隐藏状态栏

python - 在 PyObjC 中使用 NSSpeechRecognizer 类

ios - 如何使用 Realm 编写更好的数据访问层

xcode - xcode 上的 MapKit 相机使用 swift?

objective-c - 自定义 NSTextView 边框问题

ios - 在更改 VC 之前获取并存储 PanoramaView 的位置

ios - 更改 FBSDKLoginButton 的默认标题

ios - 以字符串格式获取 Web 服务响应

ios - 如何将子字符串附加到主字符串?