我尝试按照此 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);
});
});