[英]Firebase Messaging: Send a data message to all app users with a cloud function
How could I approach messaging all users of an app?我如何向应用程序的所有用户发送消息?
With the web GUI it is possible to send a notification message to all users of an app, so I assume doing the same with a function and a data message (or at least with a notification message) is possible with a function too - but I couldn't find a way to do that.使用 web GUI,可以向应用程序的所有用户发送通知消息,所以我假设对 function 和数据消息(或至少使用通知消息)也可以使用 ZC1C425268E68384F145A 但 I A找不到办法做到这一点。
I tried subscribing all devices to a topic, by calling:我尝试通过调用以下方式为所有设备订阅一个主题:
FirebaseMessaging.getInstance().subscribeToTopic("all");
In the onCreate
event of my FirebaseMessagingService
, then sending a message with a cloud function:在我的FirebaseMessagingService
的onCreate
事件中,然后使用云 function 发送消息:
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)
})
But onMessageReceived
doesn't trigger (unlike when I send a notification message using the GUI).但是onMessageReceived
不会触发(与我使用 GUI 发送通知消息时不同)。
Is this approach viable in any way?这种方法是否可行? What am I missing?我错过了什么?
I believe the only part you will need to change is the end.我相信你需要改变的唯一部分就是结尾。 You won't need this part here admin.database().ref("/messages/" + context.params.meta).remove()
.你在这里不需要这部分admin.database().ref("/messages/" + context.params.meta).remove()
。
For the messaging, your code needs to look something like the below sample:对于消息传递,您的代码需要类似于以下示例:
// 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);
});
You need to user a catch to manage the error - this way you will be able to visualize as well, what might be causing your issue.您需要使用 catch 来管理错误 - 这样您也可以可视化可能导致您的问题的原因。 You can find more information in this documentation here: Send messages to topics .您可以在此文档中找到更多信息: 向主题发送消息。
Besides that, I found this nice repository - that you can access here - with some examples and more code samples, on how to use Cloud Functions with FCM.除此之外,我发现了这个不错的存储库——您可以在此处访问——其中包含一些示例和更多代码示例,介绍了如何将 Cloud Functions 与 FCM 一起使用。
Let me know if the information helped you!让我知道这些信息是否对您有帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.