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 ...
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