Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting priority Firebase Messaging in Cloud Function for Firebase

I'm using Firebase Messaging to send notifications to users of my iPhone app. In order to not expose the app's messaging server key on the client side I'm using Cloud Function for Firebase to send the notifications to specific topics. Before this I did it from the client side on the app and was able to set the message's priority by making a JSON of this format:

// Swift code in iPhone app
let body: [String: Any] = ["to": "/topics/\(currentPet)",
                            "priority" : "high",
                            "notification" : [
                                "body" : "\(events[eventType]) for \(petsName.localizedCapitalized)",
                                "title" : "\(myName.localizedCapitalized) just logged an event",
                                "data" : ["personSent": myId]
                              ]
                           ]

Now in my cloud function I'm trying to make a payload of the same general format, but keep running into the error:

Messaging payload contains an invalid "priority" property. Valid properties are "data" and "notification".

Here's my payload formatting and sending:

const payload = {
      'notification': {
        'title': `${toTitleCase(name)} just logged an event`,
        'body': `${events[eventType]} for ${toTitleCase(petName)}`,
        'sound': 'default',
        'data': userSent 
      },
      'priority': 'high'
    };
admin.messaging().sendToTopic(pet_Id, payload);

Does anybody know how I would accomplish setting the priority? Should I just manually do an HTTP POST instead of using admin.messaging().sendToTopic()?

like image 353
MarksCode Avatar asked Nov 29 '22 22:11

MarksCode


1 Answers

From the Firebase Cloud Messaging documentation on sending messages with the Admin SDK:

// Set the message as high priority and have it expire after 24 hours.
var options = {
  priority: "high",
  timeToLive: 60 * 60 * 24
};

// Send a message to the device corresponding to the provided
// registration token with the provided options.
admin.messaging().sendToDevice(registrationToken, payload, options)
  .then(function(response) {
    console.log("Successfully sent message:", response);
  })
  .catch(function(error) {
    console.log("Error sending message:", error);
  });

The difference is that the priority (and ttl in the example) is passed as a separate options argument instead of in the payload.

like image 134
Frank van Puffelen Avatar answered Dec 04 '22 11:12

Frank van Puffelen