使用 Expo React Native 向多个设备发送推送通知

时间:2021-04-01 01:38:10

标签: firebase react-native push-notification expo

我尝试按照此 video 教程使用 Expo 和 Firebase 将一个通知推送到多台设备。我已成功将令牌存储在我的 Firebase 实时数据库中,但如何从这里开始并向存储在此设备中的所有令牌发送通知?我不能使用 expo.io 通知网站,因为它一次只允许我发送到一台设备。尽管我部署了云功能,但视频的代码不起作用。如果我将一个新孩子添加到我在 firebase 的实时数据库中的联系人/父级,它应该推送通知。我不认为它被正确触发。如果有更好的方法来做到这一点,请告诉我。这是我的 index.js:

const functions = require("firebase-functions");
const fetch = require("node-fetch");
const admin = require("firebase-admin");
admin.initializeApp(functions.config().firebase);
// send the push notification
exports.sendPushNotification = functions.database.ref("contacts/")
    .onCreate((event) => {
      const root = event.data.ref.root;
      const messages = [];

      // return the main promise
      return root.child("/user").once("value").then((snapshot) => {
        snapshot.forEach((childSnapshot) => {
          const expoToken = childSnapshot.val().expoToken;

          messages.push({
            "to": expoToken,
            "sound": "default",
            "body": "New Note Added",
          });
        });
        // firebase.database then() respved a single promise that resolves
        // once all the messages have been resolved
        return Promise.all(messages);
      })
          .then((messages) => {
            // console.log(messages)
            return fetch("https://exp.host/--/api/v2/push/send",
                {
                  method: "POST",
                  headers: {
                    "Accept": "application/json",
                    "Content-Type": "application/json",
                  },
                  body: JSON.stringify(messages),
                });
          })
          .catch((reason) => {
            console.log(reason);
          });
    });

这是我的 firebase 父用户中的令牌图片,我尝试设置通知消息的联系人父显示在其上方: enter image description here

0 个答案:

没有答案