1

我知道关于 ios 上的 nsurlconnection 的讨论,并且至少有 240 秒的超时时间。我的问题是,如果我通过 NSURLConnection 的 + (NSData *)sendSynchronousRequest:(NSURLRequest )request returnedResponse:(NSURLResponse * )response error:(NSError **)error 发送同步调用,是否有机会在240秒到了吗?我在想也许设置一个计时器来取消这个同步请求,但我什至不确定它是否可能?我在想:

[self performSelector:@selector(cancelRequest:) withObject:myRequest afterDelay:myTimeOut];

我有一种感觉,如果请求以某种方式被释放,这将导致灾难,我无法确定这一点。想法?有没有人尝试过这样做?这是一个同步调用。

4

3 回答 3

6

这似乎对我有用:

NSURL *url = [NSURL URLWithString:@"http://someurl.com"];
NSURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:5];
NSHTTPURLResponse *response = nil;
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:NULL];
if (response == nil) {
    // timed out or failed
} else {
    // all good
}

当然,将超时间隔设置为您希望它在超时之前阻塞主线程的时间 - 上面的代码在 5 秒后成功超时

在 iOS6 和 iOS5.1 中测试

于 2013-01-10T01:49:34.950 回答
6

你不能取消它。简单地不要使用它,而是使用异步调用。您可以轻松取消的那些。

于 2011-03-01T23:16:57.267 回答
1
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url    cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10.0];

webData = (NSMutableData *)[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];

if (webData==nil) {
        [self displayAlert:@"Time Out" message:@"Request Timed Out"];
    }

正好在 10 秒内超时。

于 2013-07-19T19:00:06.353 回答