I have an iOS application where the user can trigger a lengthy update process by tapping on a button. The update process involves making API calls that can take a few minutes to complete. Everything works fine when the user stays in the foreground, but if the user switches to the background, the app is not able to fetch all the necessary data.
I would like to implement a solution where, upon tapping the update button, the update process can continue running even if the app enters the background. I want to request additional background execution time to ensure that the update process completes successfully.
Based on my research, I've learned about the beginBackgroundTask(expirationHandler:)
method provided by the UIApplication
class, which allows an app to request additional background execution time. However, I'm unsure how to implement it correctly in my app.
Here's the current flow in my app:
The user taps the "Update" button, triggering the updateData()
function.
Inside updateData()
, I make the necessary API calls to fetch the required data.
If the app is in the foreground, everything works fine. However, if the app enters the background during the update process, the data fetching is incomplete.
I would like to modify the updateData()
function to request additional background execution time so that the update process can continue running until it completes, regardless of whether the app is in the foreground or background.
Could you provide guidance on how to implement this correctly? Any code examples or suggestions would be greatly appreciated.
PS. If I use a BGTask
as I understand the BGTask
only runs when user goes to the background mode. Is there any way to run the updateData()
with a BGTask
wether the app stays in foreground or background? The user might stay in foreground until the update finishes or they may go to the background. That's my main issue.
Thank you!