forcing NSUrlConnection timeout on a synchronous call
I am aware of discussions regarding nsurlconnection on ios, and that there is a minimum of 240 seconds for a timeout. My question is, if I am sending a synchronous call via NSURLConnection's + (NSData *)sendSynchronousRequest:(NSURLRequest )request returningResponse:(NSURLResponse *)response error:(NSError **)error, is there any chance I can cancel this before the 240 seconds is up? I am thinking perhaps setting a timer to cancel this synchronous request,开发者_如何学Python but im not even sure if its even possible? Im thinking:
[self performSelector:@selector(cancelRequest:) withObject:myRequest afterDelay:myTimeOut];
I have a feeling this will result in disaster if somehow the request has been released, and I would have no way to determine that. Thoughts? Has anyone tried to do this? This is a synchronous call.
You cannot cancel it. Simply don't use it and use an asynchronous call instead. Those you can easily cancel.
This seemed to work for me:
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
}
Ofcourse setting the timeout interval to how long you want it to block the main thread before timing out - The above code successfully timed out after 5 seconds
Tested in iOS6 & iOS5.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"];
}
Timeout in exactly 10 seconds.
精彩评论