Chapter 37. Basic Networking

Networking is difficult and complicated, chiefly because it’s ultimately out of your control. My motto with regard to the network is, “There’s many a slip ’twixt the cup and the lip.” You can ask for a resource from across the network, but at that point anything can happen: the resource might not be found (the server is down, perhaps), it might take a while to arrive, it might never arrive, the network itself might vanish after the resource has partially arrived. iOS, however, makes at least the basics of networking very easy, so that’s what this chapter will deal with.

Many earlier chapters have dealt with interface and frameworks that network for you automatically. Put a UIWebView in your interface (Chapter 24) and poof, you’re networking; the UIWebView does all the grunt work, and it does it a lot better than you’d be likely to do it from scratch. The same is true of MPMovieViewController (Chapter 28), MFMailComposeViewController (Chapter 33), and MKMapView (Chapter 37).

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

Get Programming iOS 5, 2nd 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.