Cookbook: Using NSURLSession

Cookbook: Using NSURLSession

Get started quick with NSURLSession!

Welcome to cooking with Chef Charlie!

Tonight’s menu doesn’t include smoked trout; but it does include three recipes for working with NSURLSession.

In this cookbook-style tutorial, you will learn how to download data, download an Image, and post data all using the NSURLSession suite of classes. Bon Apetit!

What do you need?

  • NSURLSession
  • Some data or images to download
  • A web service to POST data to
  • 5 minutes

Download some data

Downloading data from a web service is a very common task. NSURLSession makes this very easy. Check out the following code snippet

// 1
NSString *dataUrl = @"YOUR_DATA_URL";
NSURL *url = [NSURL URLWithString:dataUrl];
// 2
NSURLSessionDataTask *downloadTask = [[NSURLSession sharedSession]
  dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
  // 4: Handle response here
// 3
[downloadTask resume];
  1. Specify a URL that can return XML, a plist, JSON, etc.
  2. Create an NSURLSessionDataTask using the NSURLSession shared session. The data task is the object that does the work for you.
  3. All of the the different tasks from NSURLSession start in a suspended state. Start the task here.
  4. Handle any response in the completionHandler.

Download an Image

NSURLSession also makes it incredibly easy to download Images.

NSURL *url = [NSURL URLWithString:
// 2	
NSURLSessionDownloadTask *downloadPhotoTask = [[NSURLSession sharedSession]
 downloadTaskWithURL:url completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
  // 3 
  UIImage *downloadedImage = [UIImage imageWithData:
    [NSData dataWithContentsOfURL:location]];
// 4	
[downloadPhotoTask resume];
  1. Specify the URL of a photo. Use this one of our great fishing spot. Or you can substitute your own.
  2. Create a task from the NSURLSession. This time create a download task.
  3. An NSURLSessionDownloadTask downloads the file to a temporary location on the iOS device. In the completionHandler, you can save this file permanently. Check out the sample app code at the end of the tutorial to see how to save the image to your Photo Album.
  4. I guarantee that you will forget to start a task when working with NSURLSession :]

Posting data

You should now have a good grasp on how to download data. If you need to post data to a web service, NSURLSession can handle that too.

Until now, you have been using the convenience method [NSURLSession sharedSession] to create NSURLSessionTasks on a pre-configured session. This time, you will create a configurable NSURLSession using an NSURLSessionConfiguration object, so that you can set any attributes you may need (such as HTTP header attributes).

// 1
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
// 2
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
request.HTTPMethod = @"POST";
// 3
NSDictionary *dictionary = @{@"key1": @"value1"};
NSError *error = nil;
NSData *data = [NSJSONSerialization dataWithJSONObject:dictionary 
  options:kNilOptions error:&error];
if (!error) {
 // 4
 NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request
   fromData:data completionHandler:^(NSData *data,NSURLResponse *response,NSError *error) {
   // Handle response here
   // 5
   [uploadTask resume];
  1. First, create the NSURLSessionConfiguration and then create a session with that configuration. This allows you to create a session with specific attributes set on it. For example, your web service might require you to set an API key in the HTTP Header (see the sample project.) Note that the configuration property of an NSURLSession is read-only so any configuration needs to be done before creating the session.
  2. All of the NSURLSessionTask subclasses can be created using either an NSURL or an NSMutableURLRequest. Here, create an NSMutableURLRequest so that you can specifically set the request to be a POST.
  3. Create a JSON representation of the dictionary you will post to the web service.
  4. If everything goes OK, create the NSURLSessionUploadTask using the JSON data you created in the previous step. This will make an HTTP POST with the body set as JSON data.
  5. Don’t forget! (You will)

TroutTrip: Sample project

Well, we didn’t have any smoked trout to cook up this time. But we do have a sample app where you can track your own fishing adventures.

You can download the TroutTrip source code here. This simple application will show you all three of the above recipes by doing the following:

  1. Download weather data for our trout fishing location in RWWeatherDataTaskViewController.m. This sample uses the API (Dark Sky’s)
  2. Download a photo of our fishing spot in RWLocationDownloadTaskViewController.m
  3. Post your notes about the “one that got away” to a backend. RWStoryUploadTaskViewController.m

Note: You will need to provide your own API keys for and There are #warning pragmas in the code to show you where to enter your API keys. And, there are some helpful URLs there to follow to get more information on the two services.

Where To Go From Here?

You have just scratched the surface of what’s available with NSURLSession. For further information and examples check out these other great resources:

Cookbook: Using NSURLSession is a post from: Ray Wenderlich

The post Cookbook: Using NSURLSession appeared first on Ray Wenderlich.



Write a comment