Firebase Messaging:使用云功能向所有应用程序用户发送数据消息
Firebase Messaging: Send a data message to all app users with a cloud function
我怎样才能向应用程序的所有用户发送消息?
使用 Web GUI 可以向应用程序的所有用户发送通知消息,因此我假设对函数和数据消息(或至少是通知消息)也可以对函数执行相同的操作 - 但我找不到这样做的方法。
我的尝试
我尝试通过调用以下方式为所有设备订阅一个主题:
FirebaseMessaging.getInstance().subscribeToTopic("all");
在我的FirebaseMessagingService
的onCreate
事件中,然后用云函数发送消息:
exports.sendMessage = functions.database.ref("/messages/{meta}")
.onCreate((snapshot, context) => {
const message = snapshot._data;
console.log("msg", message["title"]);
// logs the correct data, therefore the event triggers
const payload = {
data: {
title: message["title"]
/* blah blah */
},
topic: "all"
}
admin.database().ref("/messages/" + context.params.meta).remove()
return admin.messaging().send(payload)
})
但 onMessageReceived
不会触发(与我使用 GUI 发送通知消息时不同)。
这种方法是否可行?我错过了什么?
我相信你唯一需要改变的部分就是结局。您在这里不需要这部分 admin.database().ref("/messages/" + context.params.meta).remove()
.
对于消息传递,您的代码需要类似于以下示例:
// Send a message to devices subscribed to the provided topic.
admin.messaging().send(payload)
.then((response) => {
// Response is a message ID string.
console.log('Successfully sent message:', response);
})
.catch((error) => {
console.log('Error sending message:', error);
});
您需要使用 catch 来管理错误 - 这样您也可以直观地了解可能导致问题的原因。您可以在此处的文档中找到更多信息:Send messages to topics.
除此之外,我发现了这个不错的存储库 - 您可以访问 here - 包含一些示例和更多代码示例,介绍如何将 Cloud Functions 与 FCM 结合使用。
如果这些信息对您有帮助,请告诉我!
我怎样才能向应用程序的所有用户发送消息?
使用 Web GUI 可以向应用程序的所有用户发送通知消息,因此我假设对函数和数据消息(或至少是通知消息)也可以对函数执行相同的操作 - 但我找不到这样做的方法。
我的尝试
我尝试通过调用以下方式为所有设备订阅一个主题:
FirebaseMessaging.getInstance().subscribeToTopic("all");
在我的FirebaseMessagingService
的onCreate
事件中,然后用云函数发送消息:
exports.sendMessage = functions.database.ref("/messages/{meta}")
.onCreate((snapshot, context) => {
const message = snapshot._data;
console.log("msg", message["title"]);
// logs the correct data, therefore the event triggers
const payload = {
data: {
title: message["title"]
/* blah blah */
},
topic: "all"
}
admin.database().ref("/messages/" + context.params.meta).remove()
return admin.messaging().send(payload)
})
但 onMessageReceived
不会触发(与我使用 GUI 发送通知消息时不同)。
这种方法是否可行?我错过了什么?
我相信你唯一需要改变的部分就是结局。您在这里不需要这部分 admin.database().ref("/messages/" + context.params.meta).remove()
.
对于消息传递,您的代码需要类似于以下示例:
// Send a message to devices subscribed to the provided topic.
admin.messaging().send(payload)
.then((response) => {
// Response is a message ID string.
console.log('Successfully sent message:', response);
})
.catch((error) => {
console.log('Error sending message:', error);
});
您需要使用 catch 来管理错误 - 这样您也可以直观地了解可能导致问题的原因。您可以在此处的文档中找到更多信息:Send messages to topics.
除此之外,我发现了这个不错的存储库 - 您可以访问 here - 包含一些示例和更多代码示例,介绍如何将 Cloud Functions 与 FCM 结合使用。
如果这些信息对您有帮助,请告诉我!