NSURLSession:如何增加URL请求的超时? [英] NSURLSession: How to increase time out for URL requests?

查看:1419
本文介绍了NSURLSession:如何增加URL请求的超时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

NSURLSession *session = [NSURLSession sharedSession];

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

如何增加超时值以避免错误请求超时(在 NSURLErrorDomain 代码= -1001 )?

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

我已检查 NSURLSessionConfiguration 但没有找到设置超时值的方法。

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

谢谢你你的帮助!

推荐答案

ObjC



ObjC

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



Swift



Swift

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



什么文档说



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

What docs say

timeoutIntervalForRequest and timeoutIntervalForResource specify the timeout interval for the request as well as the resource.


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

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 - 应允许
资源请求的最长时间。此值控制在放弃之前等待整个资源转移的
多长时间。
资源计时器在请求启动时启动并计数直到
请求完成或达到此超时间隔,
以先到者为准。

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类参考

这篇关于NSURLSession:如何增加URL请求的超时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆