user14367248
user14367248

Reputation: 85

Update Live Activity using remote push notification in SwiftUI

I am trying to update live activities using remote push notifications.

I am creating a live activity like this:

do{
        let activity = try Activity<LiveMatchesAttributes>.request(attributes: attributes, contentState: state, pushType: .token)

        print("Activity Added Successfully. id: \(activity.id)")
            
        Task {
           for await data in activity.pushTokenUpdates {
              let myToken = data.map {String(format: "%02x", $0)}.joined()

               print("pushToken", myToken)
               
           }
        }
        

    }catch{
        print(error.localizedDescription)
    }

The live activity shows up in the notifications center and the pushToken can also be received. Now I am trying to update the live activity using remote notifications. The code for that looks like this:

exports.updateLiveActivities = functions.https.onRequest((req, res) => {
const fcmToken = "fcmToken"


const apns = {
    headers: {
        "apns_push_type" : "liveactivity",
        "apns_topic" : "bundle_id.push-type.liveactivity",
    },

    "payload": {
        "aps": {
        "timestamp" : Date.now(),
        "event": "update",
        "content-state": {
            "event": "start"
          },
        "alert": {
            "title": "Race Update",
            "body": "Tony Stark is now leading the race!"
         }
        },

    }

}

const message = {
    token: fcmToken,
    apns: apns
}

admin.messaging().send(message).then((response) => {
    // Response is a message ID string.
    console.log('Successfully sent message:', response);
    res.send("ok")
    // return res.send("ok");
}).catch((error) => {
    console.log(error)
    return res.send(error.code);
});

});

Sending the remote notification works because the "alert" is appearing on my phone but the live activity is not getting updated. Any ideas where to insert the received "pushToken" for the live activity?

Upvotes: 4

Views: 1402

Answers (1)

Vina
Vina

Reputation: 1029

The pushToken that you get should be in the URL where you're sending the request. For example if it's to the Sandbox: https://api.sandbox.push.apple.com/3/device/insert-the-pushToken-here

This pushToken used to be the device token but for Live Activity, simply replace the device token with live activity's pushToken

Upvotes: 1

Related Questions