NSURLRequest Timeout IOS

会有一股神秘感。 提交于 2019-12-19 19:29:38

问题


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.


回答1:


This answer explains about the minimum value of timeoutInterval of an NSURLRequest object. 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:

//....
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];
}



回答2:


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;

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




回答3:


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



来源:https://stackoverflow.com/questions/11718256/nsurlrequest-timeout-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!