I'm trying to set up background HTTP upload requests (syncing files from the user's phone to a server) that trigger periodically in my Swift app. I don't have strict requirements on when this runs (it can happen overnight or throughout the day).
I know Apple provides several APIs for background tasks on iOS (beginBackgroundTask, BGAppRefreshTaskRequest, BGProcessingTaskRequest, URLSession upload vs. background session). And I've seen this post on the Apple developer forums that attempts to explain the differences and when to use which - as well as Apple's page on the subject, but it's still not clear to me how a few of these work in practice, and thus which ones I should utilize for my use case.
My questions:
- How should I schedule periodic file upload tasks in the background?
- I assume I should use
BGProcessingTaskRequest, since I don't know exactly how long the task will take (it could be syncing just 1-2 files, or it could be hundreds) and I don't care if it runs overnight
- I assume I should use
- How should I ensure foreground tasks are able to complete after closing the app? (i.e. when a user starts a sync manually in the app)
- From Apple's page on
URLSessionUploadTask: "Unlike data tasks, you can use upload tasks to upload content in the background."- Does this mean any requests I make using
URLSession.shared.upload()will automatically run in the background if the user closes the app? Even with the async/await version, or do I have to use thecompletionHandlerversion?
- Does this mean any requests I make using
- Do I need to call
beginBackgroundTaskif I'm usingURLSession.shared.upload()to guarantee I get more time to finish uploads? - What about sequential requests (i.e. requests that haven't started yet by the time the app is closed)? Based on this StackOverflow response, it sounds like I may need to trigger all the uploads in parallel beforehand? https://stackoverflow.com/a/53949607/2359478
- From Apple's page on
- Should I even consider
URLSessionConfiguration.backgroundfor my use case? It sounds like it I usebeginBackgroundTaskandBGProcessingTaskRequestthen this may be unnecessary?
Thanks!