8.2. Handling Timeouts in Asynchronous Connections
Problem
You want to set a wait limit—in other words, a timeout—on an asynchronous connection.
Solution
Set the timeout on the URL request that you pass to the NSURLConnection class.
Discussion
When instantiating an object of type NSURLRequest to pass to your URL connection,
you can use its requestWithURL:cachePolicy:timeoutInterval:
class method and pass the desired number of seconds of your timeout as
the timeoutInterval
parameter.
For instance, if you want to wait a maximum of 30 seconds to download the contents of Apple’s home page using a synchronous connection, create your URL request like so:
NSString *urlAsString = @"http://www.apple.com";
NSURL *url = [NSURL URLWithString:urlAsString];
NSURLRequest *urlRequest =
[NSURLRequest
requestWithURL:url
cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
timeoutInterval:30.0f];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection
sendAsynchronousRequest:urlRequest
queue:queue
completionHandler:^(NSURLResponse *response,
NSData *data,
NSError *error) {
if ([data length] >0 &&
error == nil){
NSString *html = [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding];
NSLog(@"HTML = %@", html);
}
else if ([data length] == 0 &&
error == nil){
NSLog(@"Nothing was downloaded.");
}
else if (error != nil){
NSLog(@"Error happened = %@", error);
}
}];What will happen here is that the runtime will try to retrieve the contents of the provided URL. If this can ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access