I want to update or end a Live Activity when the application is terminated, but those functions are async, and anything inside Task{ }
is not get called in the applicationWillTerminate(_)
function.
func applicationWillTerminate(_ application: UIApplication) {
Task {
if #available(iOS 16.2, *) {
await LiveActivityManager.cancelAllRunningActivies()
}
}
}
I have tried passing a group user default to the live activity, and live activity uses a timer to check the new value for every seconds, but timer on live activity is not get called.
Is there any way to update the live activity when the application is about to be terminated?
2
Answers
This works for me: https://developer.apple.com/forums/thread/732418
Just remember to use
Task.detached
if the entire class is marked with@MainActor
, otherwise anything inside the task will not be execute.In iOS, when the application is about to be terminated, there’s very limited time available to perform tasks. The applicationWillTerminate(_:) method is not the ideal place for performing asynchronous tasks or waiting for them to complete since there’s no guarantee that they will finish executing.
Instead, consider alternative approaches to handle your scenario use Background Tasks:
If you need to perform some tasks when your app is about to be terminated, you can request background execution time using BGTaskScheduler to ensure your tasks get some time to execute before the app is terminated. You can create a background task and schedule it to run at some point in the future. Here’s a simplified example: