Background Transfer Service

My second post on the series.

Background Transfer Service is great multitasking service to allow longer download/upload when app is in background or not running at all. I will focus on things that I learned hard way. Awesome tutorials are out there which I will put in the end of this post.

NSURLSession allows downloading, upload and fetch data. It uses HTTP hence you can choose http methods like POST, GET etc for call. NSURLSessionConfiguration is used to initialize various properties for NSURLSession object’s intend to use. Normally we have been using default configuration for general purpose

NSURLSessionConfiguration *configObject = [NSURLSessionConfiguration defaultSessionConfiguration];

For process to happen on background mode, we have background configuration

NSURLSessionConfiguration * configObject = [NSURLSessionConfiguration backgroundSessionConfiguration:@"backgroundmodeproc"];

You should know that backgroundSessionConfiguration has been deprecated so we will use

NSURLSessionConfiguration* configObject = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:identifier];

I was uploading some data or in my case I was just upload simple POST data. We create NSURLSessionUploadTask

NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request
                                                                   fromData:data completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                                                                       // Handle response here
[uploadTask resume];

I got an error

Completion handler blocks are not supported in background sessions. Use a delegate instead.

I updated the code

NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request fromData:data];

That issue got solved and new arrived.

Upload tasks from NSData are not supported in background sessions.

In the end I used NSURLSessionDownloadTask

NSURLSessionDownloadTask * downloadTask =[session downloadTaskWithURL: url];
[downloadTask resume];

Those were the things I learned. You will learn full details on well defined tutorials out there.

One Comment

Join the Discussion

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>