NSURLRequest 超时 IOS

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

NSURLRequest Timeout IOS

iphoneiosipadnsurlconnectionnsurlrequest

提问by Codesen

I need to set timeout 15sec or 30 sec with UIRequest, but it always takes default one. Is there any way to set minimum timeout to connection.

我需要使用 UIRequest 设置超时 15 秒或 30 秒,但它始终采用默认值。有什么方法可以设置连接的最小超时时间。

回答by Eren Be?el

This answerexplains about the minimum value of timeoutIntervalof an NSURLRequestobject. If you need a smaller value, then you may do so with starting an NSTimer with the desired time and in the firing method of the timer, you cancel the connection of your NSURLConnection object. As in:

这个答案解释timeoutInterval了一个NSURLRequest对象的最小值。如果您需要一个较小的值,那么您可以使用所需的时间启动 NSTimer,并在计时器的触发方法中取消 NSURLConnection 对象的连接。如:

//....
connection = [[NSURLConnection connectionWithRequest:request delegate:self] retain];
[request release];

[connection start];

if (timer == NULL) {

    timer = [NSTimer scheduledTimerWithTimeInterval: TimeOutSecond
                                             target: self
                                           selector: @selector(cancelURLConnection:)
                                           userInfo: nil 
                                            repeats: NO];
    [timer retain];
}


- (void)cancelURLConnection:(NSTimer *)timerP {
    [connection cancel]; //NSURLConnection object
    NSLog(@"Connection timeout.");
    [timer invalidate];
}

回答by EsbenB

There seems to be a problem with setting the timeout interval property at construction time:

在构建时设置超时间隔属性似乎有问题:

NSMutableURLRequest* request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:240.0];

Instead set it AFTER construction:

而是在构造后设置它:

request.timeoutInterval = 70;

request.timeoutInterval = 70;

Also note that there seem to be some limitations to how low you can set the interval. Read this post for more information: https://devforums.apple.com/message/108087#108087

另请注意,您可以设置多低的间隔似乎有一些限制。阅读这篇文章了解更多信息:https: //devforums.apple.com/message/108087#108087

回答by Sulthan

POST requests have a timeout minimum which is 4 minutes, I believe. The most secure way is to start a NSTimerand cancel the request when the timeout fires.

我相信 POST 请求的超时时间最短为 4 分钟。最安全的方法是NSTimer在超时触发时启动并取消请求。