14.7. Handling Network Connections in the Background
Problem
You are using instances of NSURLConnection to send and receive data to and from a web server and are
wondering how you can allow your application to work in the multitasking
environment of iOS without connection failures.
Solution
Make sure you support connection failures in the block objects that you submit to your connection objects.
Discussion
For applications that use NSURLConnection but do not borrow extra time
from iOS when they are sent to the background, connection handling is
truly simple. Let’s go through an example to see how an asynchronous
connection will act if the application is sent to the background and
brought to the foreground again. For this, let’s send an asynchronous connection request to
retrieve the contents of a URL (say, Apple’s home page):
-(BOOL)application:(UIApplication*)applicationdidFinishLaunchingWithOptions:(NSDictionary*)launchOptions{NSString*urlAsString=@"http://www.apple.com";NSURL*url=[NSURLURLWithString:urlAsString];NSURLRequest*urlRequest=[NSURLRequestrequestWithURL:url];NSOperationQueue*queue=[[NSOperationQueuealloc]init];[NSURLConnectionsendAsynchronousRequest:urlRequestqueue:queuecompletionHandler:^(NSURLResponse*response,NSData*data,NSError*error){if([datalength]>0&&error!=nil){/* Date did come back */}elseif([datalength]==0&&error!=nil){/* No data came back */}elseif(error!=nil){/* Error happened. Make sure you handle ...
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