【发布时间】:2019-01-23 08:44:53
【问题描述】:
我正在创建一个应用程序,当今天的日期与数据库中存储的日期匹配时,我需要发送推送通知以发送推送通知。 如何做到这一点?
【问题讨论】:
标签: firebase react-native google-cloud-firestore google-cloud-functions onesignal
我正在创建一个应用程序,当今天的日期与数据库中存储的日期匹配时,我需要发送推送通知以发送推送通知。 如何做到这一点?
【问题讨论】:
标签: firebase react-native google-cloud-firestore google-cloud-functions onesignal
更新:
您可以使用scheduled Cloud Function,而不是编写通过在线 CRON 作业服务调用的 HTTPS 云函数。 Cloud Function 代码保持不变,只是触发器发生了变化。
在编写初始答案时,计划的云功能不可用。
在不了解您的数据模型的情况下,很难给出准确的答案,但让我们想象一下,为了简化,您在每个文档中存储一个名为 notifDate 的字段,格式为 DDMMYYY,并且这些文档存储在一个名为 @ 的集合中987654328@.
您可以如下编写一个 HTTPS 云函数:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const cors = require('cors')({ origin: true });
const moment = require('moment');
admin.initializeApp();
exports.sendDailyNotifications = functions.https.onRequest((request, response) => {
cors(request, response, () => {
const now = moment();
const dateFormatted = now.format('DDMMYYYY');
admin.firestore()
.collection("notificationTriggers").where("notifDate", "==", dateFormatted)
.get()
.then(function(querySnapshot) {
const promises = [];
querySnapshot.forEach(doc => {
const tokenId = doc.data().tokenId; //Assumption: the tokenId is in the doc
const notificationContent = {
notification: {
title: "...",
body: "...", //maybe use some data from the doc, e.g doc.data().notificationContent
icon: "default",
sound : "default"
}
};
promises
.push(admin.messaging().sendToDevice(tokenId, notificationContent));
});
return Promise.all(promises);
})
.then(results => {
response.send(data)
})
.catch(error => {
console.log(error)
response.status(500).send(error)
});
});
});
然后,您将每天使用在线 CRON 作业服务(如 https://cron-job.org/en/)调用此 Cloud Function。
有关如何在 Cloud Functions 中发送通知的更多示例,请查看这些 SO 答案 Sending push notification using cloud function when a new node is added in firebase realtime database?、node.js firebase deploy error 或 Firebase: Cloud Firestore trigger not working for FCM。
如果您不熟悉 Promises 在 Cloud Functions 中的使用,我建议您观看 Firebase 视频系列中关于“JavaScript Promises”的 3 个视频:https://firebase.google.com/docs/functions/video-series/
您会注意到上面代码中使用了Promise.all(),因为您正在并行执行多个异步任务(sendToDevice() 方法)。这在上面提到的第三个视频中有详细说明。
【讨论】:
使用 Google Cloud Functions 计划触发器 https://cloud.google.com/scheduler/docs/tut-pub-sub
使用计划触发器,您可以通过使用 unix-cron 格式指定频率来指定调用函数的次数。然后在函数内你可以做日期检查和其他需要的逻辑
【讨论】: