Downloading Data using NSURLSession in IOS using Objective-C

Downloading Data using NSURLSession in IOS using Objective-C

Whether an app retrieves application data from a server, updates your social media status or downloads remote files to disk, it’s the HTTP network requests living at the heart of mobile applications that make the magic happen. To help you with the numerous requirements for network requests, Apple provides URLSession, a complete networking API for uploading and downloading content via HTTP.

Unlike NSURLConnection, where we generally create a connection per request, with NSURLSession, we create one session and instead have multiple tasks.

So lets define our Session:

What we’re doing first, is creating a configuration, which will allow it to run in the background. The config needs a unique identifier specific to your app. It’s good practice to use your app’s bundle identifier, such as com.yourCompany.appName.

Once we have our configuration we can instantiate our session, where we pass in the reference to our delegate and what queue we want it to run on. You most like will want this to be the mainQueue.

For the purpose of this topic, we’re going to just tacking downloading tasks. So, once your have the URL to the file you want to download, you can create a downloadTask via your session:

Now the way, NSURLSession works, is that it downloads your file directly to a temporary directory. So you don’t need to worry about storing it.

While its downloading though, it will notify you of how much has been downloaded, which is great for notifying your users of the download progress:

Once the file is downloaded the following method will be called:

The last parameter of that method is the location of which the data was downloaded to. From here, you can move the file to a permanent place where you can work with it, or you can access the data and do something with it. However, that data won’t stay there, so make sure you don’t leave it, if you really need it.

It’s worth noting that Tasks, just like a NSURLConnection can be cancelled:

And that about covers the basics of downloading a file using NSURLSession.