Original Tutorial: http://www.raywenderlich.com/51127/nsurlsession-tutorial
The NSURLSession suite of classes
NSURLSession
is both a new class and a suite
of classes which are also the new tools to upload, download, handle authorization... To own some HTTP protocol knowledge may helpful for u to handle the usage of NSURLSession.
The following gram shows the major classes in the NSURLSession
suite
and how they work together:
An NSURLSession
is
made using an NSURLSessionConfiguration
withan
optional delegate. Creating NSURLSessionTask’s after
create the session. It can satisfy the networking needs.
NSURLSessionConfiguration
Following are the three ways to create an NSURLSessionConfiguration
:
-
defaultSessionConfiguration
– creates a configuration object that uses the global cache, cookie and credential storage objects. Make the session to be the most likeNSURLConnection
. -
ephemeralSessionConfiguration
– this configuration is for “private” sessions and has no persistent storage for cache, cookie, or credential storage objects. -
backgroundSessionConfiguration
– this is the configuration to use when you want to make networking calls from remote push notifications or while the app is suspended.
NSURLSessionConfiguration *sessionConfig =
[NSURLSessionConfiguration defaultSessionConfiguration];
// 1
sessionConfig.allowsCellularAccess = NO;
// 2
[sessionConfig setHTTPAdditionalHeaders:
@{@"Accept": @"application/json"}];
// 3
sessionConfig.timeoutIntervalForRequest = 30.0;
sessionConfig.timeoutIntervalForResource = 60.0;
sessionConfig.HTTPMaximumConnectionsPerHost = 1;
- Here restrict network operations to wifi only.
- This will set all requests to only accept JSON responses.
- These properties will configure timeouts for resources or requests. Also can restrict your app to only have one network connection to a host.
NSURLSession
NSURLSession
is designed as a replacement API
for NSURLConnection
.
Sessions do all of their work via NSURLSessionTask
objects.
With NSURLSession
you can create the tasks using
the block based convenience methods, setup a delegate, or both. For example, if you want to download an image, you will need to create an NSURLSessionDownloadTask
.
How-to
Step 1 - Create the session
(1) What we want to download
NSString *imageUrl =
@"http://www.bayequest.info/460/Large/thomas-head-8-26-11.jpg";
(2) start by creating an NSURLConfiguration
NSURLSessionConfiguration *sessionConfig =
[NSURLSessionConfiguration defaultSessionConfiguration];
(3) creates a session using the current class as a delegate
NSURLSession *session =
[NSURLSession sessionWithConfiguration:sessionConfig
delegate:self
delegateQueue:nil];
Step 2 -creating a task with a completion handler
(1) created with the block-based method - sessions create the tasks
NSURLSessionDownloadTask *getImageTask =
[session downloadTaskWithURL:[NSURL URLWithString:imageUrl]
completionHandler:^(NSURL *location,
NSURLResponse *response,
NSError *error) {
(2) use the location variable provided in the completion handler to get a pointer to the image
UIImage *downloadedImage =
[UIImage imageWithData:
[NSData dataWithContentsOfURL:location]];
(3) update UIImageView’s image to show the new file
dispatch_async(dispatch_get_main_queue(), ^{
// do stuff with image
_imageWithBlock.image = downloadedImage;
});
}];
(4) start up the task!
[getImageTask resume];
Following is the using of the
NSURLSessionDownloadDelegate
to
track download progress: ( not sure, maybe there are some mistakes)NSURLSessionDownloadTask *getImageTask =
[session downloadTaskWithURL:[NSURL URLWithString:imageUrl]];
[getImageTask resume];
-(void)URLSession:(NSURLSession *)session
downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location
{
UIImage *downloadedImage =
[UIImage imageWithData:
[NSData dataWithContentsOfURL:location]];
}
-(void)URLSession:(NSURLSession *)session
downloadTask:(NSURLSessionDownloadTask *)downloadTask
didWriteData:(int64_t)bytesWritten
totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
NSLog(@"%f / %f", (double)totalBytesWritten,
(double)totalBytesExpectedToWrite);
}
NSURLSessionTask
is
the real workhorse for “getting stuff done” over the network.
NSURLSessionTask
Notice about NSURLSessionDataTask
and NSURLSessionDownloadTask
.
Both of these tasks are derived from NSURLSessionTask
the
base class for both of these:
In the session NSURLSessionTask
is
the base class for tasks.
they can only be created from a session and are one of the following subclasses:
NSURLSessionDataTask
NSURLSessionDataTask task issues HTTP GET requests to pull down data from servers. The data is returned in form of NSData. You would then convert this data to the correct type XML, JSON, UIImage, plist etc.
NSURLSessionDataTask *jsonData = [session dataTaskWithURL:yourNSURL
completionHandler:^(NSData *data,
NSURLResponse *response,
NSError *error) {
// handle NSData
}]
NSURLSessionUploadTask
Use NSURLSessionUploadTask when need to upload something to a web service using HTTP POST or PUT commands. The delegate for tasks also allows you to watch the network traffic while it’s being transmitted.
NSData *imageData = UIImageJPEGRepresentation(image, 0.6);
NSURLSessionUploadTask *uploadTask =
[upLoadSession uploadTaskWithRequest:request
fromData:imageData];
NSURLSessionDownloadTask
NSURLSessionDownloadTask
makes it super-easy
to download files from remote service and pause and resume the download at will.
- This type of task writes directly to a temporary file.
- During the download the session will call URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite: to update status information
- When the task is finished, URLSession:downloadTask:didFinishDownloadingToURL: is called. This is when you can save the file from the temp location to a permanent one.
-
When the download fails or is cancelled you can get the data to resume the download.
All of the above
All of the above tasks are created in a suspended state; after creating one you need to call its resume method as demonstrated below:
The taskIdentifier property allows you to uniquely identify a task within a session when you’re managing more than one task at a time.[uploadTask resume];
- This type of task writes directly to a temporary file.
- During the download the session will call URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite: to update status information
- When the task is finished, URLSession:downloadTask:didFinishDownloadingToURL: is called. This is when you can save the file from the temp location to a permanent one.
- When the download fails or is cancelled you can get the data to resume the download.