简体   繁体   中英

Firebase Push Notification not being sent to the second device

I'm trying to implement push notification using firebase in my project but not being able to do so.Below is my index.js file, i have very little knowledge about javascript and nodejs and thats why not being able to figure out the problem.

     'use strict'

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();


    exports.sendNotification = functions.database.ref('/Notifications/{receiver_id}/{notification_id}').onWrite((data,context) =>
    {
      const receiver_id = context.params.receiver_id;
      const notification_id = context.params.notification_id;
      console.log('We have new notification to send to : ', receiver_id);



        /*if(!context.data.val()){

            return console.log('A notification has been deleted from the databse : ', notification_id);
        }*/

    const deviceToken = admin.database().ref(`Users/${receiver_id}/device_token`).once('value');

    return deviceToken.then(result => {

        const token_id = result.val();

        const payload = {
                notification: {

                    title : "Friend Request",
                    body : "You've received a new Friend Request",
                    icon : "default"
                }
        };

        return admin.messaging().sendToDevice(token_id,payload).then(response => {

            console.log('This was the notification feature');
            return true;

        });


    });

});

Can anyone please explain me this code and help out with my problem.

Every device has a different token. Seems you are storing only one token for one user. That's why you can send the notification to only one device. If you want to send it to multiple devices you have to store multiple device tokens and send the notification to all those devices.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM