iosswiftxcodeios-background-modeactivitykit

how to start a liveActivity from a remote notification • Swift


When implementing lock screen live activity widget for debugging purposes I had a button which runs startLiveActivity() function, app runs normaly widget appears totally functioning.

However I need this activity widget to appear whenever the app receives a remote push notification when the app is killed or in background, but it is appearing only when app is in foreground which doesn't really help the case here.

class LiveActivityHelper: ObservableObject {
    
    static var shared = LiveActivityHelper()
    
    @Published var activity: Activity<Attributes>? = nil

    func startLiveActivity() {
        
        let state = Attributes.ContentState()
        
        activity = try? Activity<Attributes>.request(attributes: Attributes(), contentState: state, pushType: nil)

    }

I tried running the startLiveActivity() function from appDelegate's didReceiveRemoteNotification:

func userNotificationCenter(_ center: UNUserNotificationCenter,
                                didReceive response: UNNotificationResponse) async {
        
        LiveActivityHelper.shared.startLiveActivity()
}

And from a notification extension I have:

class NotificationService: UNNotificationServiceExtension, UNUserNotificationCenterDelegate {

    var contentHandler: ((UNNotificationContent) -> Void)?
    var bestAttemptContent: UNMutableNotificationContent?

    override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {

    ...
    LiveActivityHelper.shared.startLiveActivity()

All these approaches lead to the same result, the widget appearing only when the app is opened.

Apple's documentation included updating the widget from a remote notification but not how to start it using that approach.


Solution

  • You can now start a Live Activity with a push notification beginning with iOS 17.2 (currently in beta).

    Request a pushToStartToken and use that to send a specific payload to your app. This will start a live activity & grant some background run time allowing you to get the live activity set up, grab the update token, etc.

    More info: https://developer.apple.com/documentation/activitykit/starting-and-updating-live-activities-with-activitykit-push-notifications