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]; |
- Specify a URL that can return XML, a plist, JSON, etc.
- Create an
NSURLSessionDataTask
using the NSURLSession shared session. The data task is the object that does the work for you. - All of the the different tasks from
NSURLSession
start in a suspended state. Start the task here. - Handle any response in the completionHandler.
Download an Image
NSURLSession
also makes it incredibly easy to download Images.
//1 NSURL *url = [NSURL URLWithString: @"http://upload.wikimedia.org/wikipedia/commons/7/7f/Williams_River-27527.jpg"]; // 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]; |
- Specify the URL of a photo. Use this one of our great fishing spot. Or you can substitute your own.
- Create a task from the
NSURLSession
. This time create a download task. - 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. - 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 NSURL *url = [NSURL URLWithString:@"YOUR_WEBSERVICE_URL"]; 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]; } |
- 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 theconfiguration
property of an NSURLSession is read-only so any configuration needs to be done before creating the session. - All of the
NSURLSessionTask
subclasses can be created using either an NSURL or anNSMutableURLRequest
. Here, create anNSMutableURLRequest
so that you can specifically set the request to be a POST. - Create a JSON representation of the dictionary you will post to the web service.
- 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. - 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:
- Download weather data for our trout fishing location in RWWeatherDataTaskViewController.m. This sample uses the forecast.io API (Dark Sky’s)
- Download a photo of our fishing spot in RWLocationDownloadTaskViewController.m
- Post your notes about the “one that got away” to a Parse.com backend. RWStoryUploadTaskViewController.m
Note: You will need to provide your own API keys for forecast.io and parse.com. 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:
- iOS 7 by Tutorials
- Our NSURLSession Tutorial
- Another popular and advanced networking library – AFNetworking 2.x tutorial
- Apple NSURLSession Intro
- WWDC 2013 Session 705 – “What’s new in Foundation Networking”
Cookbook: Using NSURLSession is a post from: Ray Wenderlich
The post Cookbook: Using NSURLSession appeared first on Ray Wenderlich.