I was following this tutorial from Udacity where Cloud Functions for Firebase was used to change the data of a ref on data added. I wanted to use similar function, but for sending a push notification to users subscribed to topic.
This is the function I am using.
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNotification = functions.database.ref('/messages/{pushId}/text').onWrite((event) => {
const data = event.data;
console.log('Message received');
if(!data.changed()){
console.log('Nothing changed');
return;
}else{
console.log(data.val());
}
const payLoad = {
notification:{
title: 'Message received',
body: 'You received a new message',
sound: "default"
}
};
const options = {
priority: "high",
timeToLive: 60*60*2
};
return admin.messaging().sendToTopic("Message_Notifications", payLoad, options);
});
Looking at the Firebase function log I can see that the function gets called when I add a new value to the database. The I am subscribing to the topic in the mainactivity with
FirebaseMessaging.getInstance().subscribeToTopic("Message_Notification");
And after a few hours now I can see the topic in my topics list in firebase notification console. I send a notification from there and it worked.
What are the other things I need to do to have a notification show up every time a new message is added?
Any suggestion is appreciated. I am fairly new to Firebase. So if there is a better blog/post about it please redirect me so that I can learn more.
Thanks in advance.