Ciaránimo
Ciaránimo

Reputation: 537

How to send push notifications to specific users with Cloud Functions for Firebase

I am using Firebase as my back end for my Android app and am very new to using Cloud Functions for Firebase and I was wondering how I would send specific users push notification when an event occurs.

For example how would I send the user with uId in the below code a push notification when a write occurs at adminName node on the database:

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);
        });
    });

Upvotes: 3

Views: 4800

Answers (1)

Fahmida
Fahmida

Reputation: 1220

Make the below changes. it works for me

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);
}
});

Upvotes: 1

Related Questions