yurgis
yurgis

Reputation: 4077

Does it make sense to use background nsurlsession and background tasks during background fetch?

If an app relies on background fetch and needs to do some handling if the fetched data is not empty, does it make sense to do:

1) fetch data with background NSURLSession (using backgroundSessionConfigurationWithIdentifier)

2) handle data in a background task (using beginBackgroundTask)

Since the system gives 30 seconds to complete a background fetch, it seems like neither #1 or #2 are really needed. The documentation (https://developer.apple.com/library/content/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html) does not explicitly say anything on whether these techniques can be combined, so I just seek for confirmation.

Upvotes: 3

Views: 2152

Answers (1)

yurgis
yurgis

Reputation: 4077

All right, after some digging with backgrounding I think I can at least partially answer my own question for those who still wonder.

  1. Background Fetch with Background-configured NSURLSession

    • The app has only 30 seconds to complete download during background fetch. If an entire download flow takes time less than this limit, it is fine to use default URLSession (without background configuration).

    • However if the resource being loaded is large, it makes perfect sense to spend given 30 seconds (or less) for the prep and initiate URLSession with background configuration. Once configured, your NSURLSession object will seamlessly hand off download tasks to the system, so that resource transfer will not be a subject of 30 second completion limit.

  2. Background Fetch with Background Tasks

    • Using a background task an app can delay suspension by at most 3 minutes in order to complete a relatively long running task (e.g. a short file upload, download, file i/o, etc) that may have been initiated by the user while being in foreground.
    • Contrary to many examples available in StackOverflow, you do not need to wait until your app moves to the background. A task that takes less than 3 minutes of time can be executed within beginBackgroundTask / endBackgroundTask, even while your app is executing in the foreground. I would go ahead and claim that it is a mistake almost in every case you run such a task without beginBackgroundTask / endBackgroundTask scope, as it is much more painful to write code that handles applicationDidEnterBackground to track completion of long running tasks started as a result of user interaction with UI.
    • If a download job is desired to be initiated by both UI and System's Background Fetch, it is perfectly fine to reuse the same code thus combining the two techniques together.

Upvotes: 6

Related Questions