raouf Mehdid
raouf Mehdid

Reputation: 43

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.

Upvotes: 1

Views: 4136

Answers (2)

iSpain17
iSpain17

Reputation: 3053

Beginning with iOS 17.2, you can now start a live activity with a push notification.

—————————————-

Up to iOS 17.1:

A Live Activity can only be started while the app is in foreground, because its purpose is to track a user-initiated feature, based on documentation.

Send your push notification, have your user open your app with it, then start the activity. Your desired flow is explicitly stated to be unsupported.

Upvotes: 3

Spaceman Spiff
Spaceman Spiff

Reputation: 731

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

Upvotes: 6

Related Questions