Is it possible to continue a NSURLSessionDataTask in background?

Hi guys,


I think that I have a conceptual problem. I have been reading documents "App Programming Guide for iOS" and "URL Loading System Programming Guide" and I have any question.


I would like to upload a NSData over network to a server. The information is very simple. I believe that I do not need save it in a file. I store it locally in Core Data and then my intention is upload it to my server. This is easy using a NSURLSessionDataTask or NSURLSessionUploadTask with "fromData" method but my questions are: "What happen if my app state moves from foreground to background before the request ends? Does the request will continue running for a limited time in background?"


NSURLSessionDataTask and NSURLSessionUploadTask (using "fromData" method) are not compatibles with a background session.


Thank you. Regards.

Accepted Answer

What happen if my app state moves from foreground to background before the request ends?

Unless you have other work that prevents your app from being suspended (for example, audio playback), it will be suspended shortly after moving to the background.

Does the request will continue running for a limited time in background?

No.

You can, however, arrange to do this by using a UIApplication background task. This is exactly what UIApplication background tasks were designed for.

Presumably your upload is small (after all, it fits in memory), so there’s a reasonable chance of it finishing in the few minutes that the UIApplication background task gives you. If it’s large enough that that’s not the case, you should use an NSURLSession background session. However, NSURLSession background sessions bring in all sorts of complexities, so if you can get away with using a foreground session in concert with a UIApplication background task, you should do so.

Share and Enjoy

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

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

Hi Quinn,


Thank you very much 🙂. Work with a UIApplication background task is the option that I had considered after read document "App Programming Guide for iOS". However, I wanted to check if there are more efficient alternatives.


Thank you again.

Is it possible to continue a NSURLSessionDataTask in background?
 
 
Q