HTTP Requests

A simple HTTP request is made through an NSURLConnection object. You hand it an NSURLRequest describing what you’d like to do, and start the download. The actual network operations happen asynchronously (unless you specifically demand that they happen synchronously, which you’d never do); in other words, the NSURLConnection object does all its work in the background. Data received from the network in response to your request will arrive as an NSData object.

For the very simplest cases, you can download a resource asynchronously without using a delegate: call the class method sendAsynchronousRequest:queue:completionHandler:. This creates an NSURLConnection and starts the download immediately. When the download ends, whether in failure or success, the completion handler block is called on the NSOperationQueue you specified, with three parameters: an NSURLResponse, an NSData (which will be the entire download if the download succeeded), and an NSError object. Here’s an example of downloading a JPEG image file and displaying it in the interface; I specify the main queue (the queue of the main thread), because my completion handler is going to talk directly to my app’s interface (see also Chapter 38):

NSString* s = @"http://www.someserver.com/somefolder/someimage.jpg"; NSURL* url = [NSURL URLWithString:s]; NSURLRequest* req = [NSURLRequest requestWithURL:url]; NSOperationQueue* q = [NSOperationQueue mainQueue]; [NSURLConnection sendAsynchronousRequest:req queue:q completionHandler:^(NSURLResponse ...

Get Programming iOS 6, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.