我使用Firebase作为我的Android应用程序的后端,并且使用Cloud Functions for Firebase非常新,我想知道如何在事件发生时发送特定用户推送通知。
例如,当在数据库的adminName节点上发生写入时,如何向下面的代码中的uId用户发送推送通知:
exports.sendNotification = functions.database.ref('/users/{uId}/groups/{adminName}')
.onWrite(event => {
// Grab the current value of what was written to the Realtime Database.
var eventSnapshot = event.data;
var str1 = "Author is ";
var str = str1.concat(eventSnapshot.child("author").val());
console.log(str);
var topic = "android";
var payload = {
data: {
title: eventSnapshot.child("title").val(),
author: eventSnapshot.child("author").val()
}
};
// Send a message to devices subscribed to the provided topic.
return admin.messaging().sendToTopic(topic, payload)
.then(function (response) {
// See the MessagingTopicResponse reference documentation for the
// contents of response.
console.log("Successfully sent message:", response);
})
.catch(function (error) {
console.log("Error sending message:", error);
});
});
答案 0 :(得分:1)
进行以下更改。它对我有用
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().functions);
var newData;
exports.myTrigger = functions.firestore.document('TestCollection/{id}').onWrite(async (snapshot, context) => {
//
if (snapshot.empty) {
console.log('No Devices');
return;
}
newData = snapshot.data();
const deviceIdTokens = await admin
.firestore()
.collection('DeviceIDTokens')
.get();
var tokens = [];
for (var token of deviceIdTokens.docs) {
tokens.push(token.data().device_token);
}
var payload = {
notification: {
title: 'Push Title',
body: 'Push Body',
sound: 'default',
},
data: {
push_key: 'Push Key Value',
key1: newData.data,
},
};
try {
const response = await admin.messaging().sendToDevice(tokens, payload);
console.log('Notification sent successfully');
} catch (err) {
console.log(err);
}
});
答案 1 :(得分:0)
尝试完成本教程。它将解决您的很多疑问 https://aaronczichon.de/2017/03/13/firebase-cloud-functions/
由于Firebase云功能非常新,您可能无法在互联网上找到关于它的材料,但本教程将帮助您了解许多功能。 我希望它有所帮助。
快乐编码