The app I develop allows user to store chosen file in encrypted form inside app directory (local). Now, lets say user wants to open a big file (>1gb) that is stored inside app. This can take quite some time, as I have the file split into multiple ones and need to decrypt them. What would be the procedure to allow this to work even when the app is suspended? As it is somewhat similar to upload/download, would want to use URLSession
in background, but it does not support local files. I guess I could be using beginBackgroundTask
, but it has limited execution time and it would feel like a hack (if user returns to app, I again beginBackgroundTask and continue to do this until task completes). Any suggestions? To be clear - all tasks are started in foreground and I don't want to use scheduling, as user would like to get the file as soon as possible.
EDIT, some usecases to maybe clarify situation a bit:
My app allows storing user selected files inside app (no cloud) in encrypted form. If selected file is big (>1gb), this operation could take several minutes to complete so I would like to allow user to do other things on his device while my app is processing the file in background. I know that I could implement this with background scheduling to this at the later date, but lets consider another example - user wants to open the big encrypted file that is stored inside app. As the user expects the result as soon as possible, scheduling for later is out of the question.
This is an obvious candidate for beginBackgroundTask
. You had two concerns:
Re “limited execution time,” that’s true, but does your task really require more than 30 seconds? (If you really need more than 30 seconds, then next logical candidate is BGProcessingTask
, but I would hesitate to add that complexity if not needed.)
Re “if user returns to app, I again beginBackgroundTask
,” the obvious suggestion would be to simply keep track of whether the task has been in started, and not relaunch it unnecessarily. Personally, I would start it as soon as the use selects it, and before you begin the task, just keep track of whether they’ve already started it or not. But this beginBackgroundTask
is not something you defer until the app leaves foreground state, but rather would start it as soon as the user taps on it.
Bottom line, I would recommend beginBackgroundTask
if this will always take less than 30 seconds. If it might exceed that, then you may have to consider BGProcessingTask
of BackgroundTasks framework, which will give you more time, but puts you at the mercy of the OS as to when the task will run.
See Choosing Background Strategies for Your App. Also, IIRC, WWDC 2020 video Background execution demystified outlines these options.