9.1. Downloading Asynchronously with NSURLConnection


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


Use the NSURLConnection class with an asynchronous request.


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 6 Programming Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.