8.1. Downloading Asynchronously with NSURLConnection

Problem

You want to download a file from a URL, asynchronously.

Solution

Use the NSURLConnection class with an asynchronous request.

Discussion

There are two ways of using the NSURLConnection class. One is asynchronous and the other is synchronous. Asynchronous connection will create a new thread and does its downloading process on the new thread. Synchronous connection will block the calling thread while downloading content and doing its communication.

Many developers think that a synchronous connection blocks the main thread, but that is incorrect. A synchronous connection will always block the thread from which it is fired. If you fire a synchronous connection from the main thread, yes, the main thread will be blocked. But if you fire a synchronous connection from a thread other than the main thread, it will be like an asynchronous connection in that it won’t block your main thread. In fact, the only difference between a synchronous and an asynchronous connection is that the runtime will create a thread for the asynchronous connection, while it won’t do such thing for a synchronous connection.

In order to create an asynchronous connection, we need to:

  1. Have our URL in an instance of NSString.

  2. Convert our string to an instance of NSURL.

  3. Place our URL in a URL Request of type NSURLRequest, or in case of mutable URLs, in an instance of NSMutableURLRequest.

  4. Create an instance of NSURLConnection and pass the URL request to it.

We can create ...

Get iOS 5 Programming Cookbook 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.