Dismiss Live Activities on App Termination

I support Live Activities in my app, and am unable to dismiss Live Activities when the app gets closed from the background.

Currently, I subscribe to the willTerminateNotification notification in order to perform actions when the app gets terminated. This guys triggered when the app gets terminated in the foreground. However, if it gets terminated from the background, it does not get triggered and my Live Activity stays after the app gets closed. How can I prevent this from happening?

I'm stuck in the same situation, I was working with a live activity that creates a timer but I closed the app and couldn't get the timer to stop until I deleted the app, I even tried restarting my phone which did not help at all.

Assuming you're using something like this to end your live activities when the app is being terminated:

  class func stopLiveActivities()
  {
		print("Ending Live Activities")
		Task
		{
			for activity in Activity<TimeoutActivityAttributes>.activities
			{
				print("Ending Live Activity: \(activity.id)")
				await activity.end(nil, dismissalPolicy: .immediate)
			}
		}
	}

This will not end the activities, the method returns and allows the app to terminate before the activities get a chance to actually end.

Add a semaphore to force it to wait for the activities to end before returning from the method:

	class func stopSessionTimeoutAsync()
	{
		print("Ending Live Activities")
		let semaphore = DispatchSemaphore(value: 0)
		Task
		{
			for activity in Activity<TimeoutActivityAttributes>.activities
			{
				print("Ending Live Activity: \(activity.id)")
				await activity.end(nil, dismissalPolicy: .immediate)
			}
			semaphore.signal()
		}
		semaphore.wait()
	}

This works for me (tested with a single activity). With the app in the background and live activity showing, I can force-kill the app and the live activity is removed.

Where should this code be added in order to kill the Live Activity when the app is closed?

Dismiss Live Activities on App Termination
 
 
Q