How to transfer tasks from default NSURLSession into background session?

We have created NSURLSession with default configuration. We used upload tasks for POST requests. We post certain string parameters in request body. When app is in foreground everything works fine.



Q1. If we start a upload task and then push the app in background . If the task is incomplete when the app goes in background then how to add those tasks to background session for further completion?


Do we need to use [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) to collect ongoing/completed tasks? Then iterate the arrays to check whether the task is complete or not and if not complted then create a new task with background session.


Q2.Should we create task with background session right from beginning instead of using default configuration?If we do so then it will always execute in a separate process.


Q3.Came across following information on Apple docs :”Only upload tasks from a file are supported (uploads from data instances or a stream fail after the app exits).”

Our request body consists of NSData instances. Is there any other drawback in using these data instances other than the app exit scenario case?

Replies

If the task is incomplete when the app goes in background then how to add those tasks to background session for further completion?

There’s no general-purpose way to transfer a task from one session to another. For some types of tasks you can do this — for example, in a download task you can cancel the task in one session and resume it another — but that approach is very task specific.

Should we create task with background session right from beginning instead of using default configuration?

Probably, although it really depends on how long the upload takes. See below for more.

If we do so then it will always execute in a separate process.

Yes.

Our request body consists of

NSData
instances.

Hmmm. The fact that you’re using an

NSData
implies that the uploads are small (if they were large, uploading from memory would likely run you out of memory) and thus are expect to complete promptly. In that case, you probably don’t want to use a background session. Rather, continue using a standard session and use a
UIApplication
background task to keep you app from suspended while the upload completes.

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"