I am using DispatchQueue.global(qos: .background).async and DispatchQueue.main.async for firebase token updation. But I feel like the code block written inside DispatchQueue.global(qos: .background).async and DispatchQueue.main.async is not getting executed. What are the best practices for running in background by making sure that the code block gets executed even if app is in background or foreground for a longer period of time or if the device kills the application.

1

There are 1 answers

0
Rob On

You said:

I am using DispatchQueue.global(qos: .background).async and DispatchQueue.main.async for firebase token updation. But I feel like the code block written inside DispatchQueue.global(qos: .background).async and DispatchQueue.main.async is not getting executed.

I would suggest that you introduce some logging to eliminate any ambiguity. Do some tests to confirm whether this code is actually getting reached or not.

Note, when testing background execution, do not do this from the Xcode debugger (as that alters the lifecycle of an app), but rather launch the app independent of the Xcode debugger and observe these logging statements from the macOS Console app.

You can use Logger and watch from your macOS Console app (as discussed in WWDC 2020 video Explore logging in Swift).

What are the best practices for running in background by making sure that the code block gets executed even if app is in background …

You can request a little more execution time should the user leave the app. See Choosing Background Strategies for Your App, notably the Continue Foreground Work in the Background section. That handles the use-case of a user leaving your app.

Basically, by calling beginBackgroundTask(withName:expirationHandler:), should the user happen to leave the app, you are requesting that the OS give you a little extra time to complete execution of some task before the app is suspended and execution stops. When you call endBackgroundTask(_:) when your asynchronous work is done, that tells the OS that you are done with your background execution, and the OS should feel free to suspend the app as appropriate. This mechanism only gives you 30 seconds, or so, but it is enough for most asynchronous tasks such as this.

… or foreground for a longer period of time …

This part of the question makes no sense to me: If the app is running in the foreground, then it is just running, and of course anything dispatched via GCD should have a chance to execute. If your dispatched code is really not running, then it must be deadlocked or the like. So, again, confirm whether it ever reaches this dispatched code or not.

… or if the device kills the application.

If the user force-quits the app, that kills everything. The app is terminated and no execution can proceed.