How to send notification to multiple device token using firebase cloud functions

烂漫一生 提交于 2021-02-11 12:10:12

问题


I am new in using Firebase Cloud Functions and JavaScript and I was able to send notification to a single device using Firebase Cloud Functions(JavaScript). Now I am trying to send push notification to multiple device token and I think I have a problem on it.

I want to send the notification to these device tokens in my firebase database:

/receivers
      /event1
           /uid1: device_token1
           /uid2: device_token2
           /uid3: device_token3
           /uid4: device_token4

This is my code so far but it doesn't work..

exports.sendSOSNotif = functions.database.ref('/SOSNotifs/{sosId}').onWrite((data, context) => {

  const eventId=data.after.child("eventId").val();
  const uid=data.after.child("uid").val();
  const displayName=data.after.child("displayName").val();
  const photoUrl=data.after.child("photoUrl").val();
  const status=data.after.child("status").val();

  console.log("eventId:", eventId);
  console.log("displayName:", displayName);
  console.log("uid", uid);

  const payload = {
    notification: {
        title: "SOS Alert",
        body: displayName + " sent an alert!",
        sound: "default"
    },

    data: {
        eventId: eventId,
        displayName: displayName
    }
  };

return Promise.all([admin.database().ref("/receivers/event1").once('value')]).then(results => {
const tokens = results[0];
if (!tokens.hasChildren()) return null;

const tokensList = Object.keys(tokens.val());
return admin.messaging().sendToDevice(tokensList, payload);

});
});

回答1:


First of all, you shouldn't be adding tokens like below, if that's how you've organised your DB. There might be multiple token for a single uid

/receivers
  /event1
       /uid1: device_token1
       /uid2: device_token2
       /uid3: device_token3
       /uid4: device_token4

And for sending notifications to multiple UIDs, I've written a script here

Also, update your question about what exactly the problem you are facing.



来源:https://stackoverflow.com/questions/57533715/how-to-send-notification-to-multiple-device-token-using-firebase-cloud-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!