1

I recently developed an application for a school and one of its features is principal's updates. For this, I'm using the Firebase database for this (on Android studio and Xcode). I heard that there is a new Firebase feature that calls cloud functions and I heard that I can integrate Database and FCM. For now, I have this code in index.js:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
// // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-functions
//
// exports.helloWorld = functions.https.onRequest((request, response) => {
//  response.send("Hello from Firebase!");
// });
exports.sendNotifications = functions.database.ref('/messageS/{id}').onWrite(event => {
  const snapshot = event.data;
  // Only send a notification when a message has been created.
  if (snapshot.previous.val()) {
    return;
  }

  // Notification details.
  const text = snapshot.val().text;
  const payload = {
    notification: {
      title: 'new message recived',
      body: text ? (text.length <= 100 ? text : text.substring(0, 97) + '...') : '',
      icon: '/app/src/main/res/drawable/logo_he_digita_homepage.png'
    }
  };

  // Get the list of device tokens.
  return admin.database().ref('fcmTokens').once('value').then(allTokens => {
    if (allTokens.val()) {
      // Listing all tokens.
      const tokens = Object.keys(allTokens.val());

      // Send notifications to all tokens.
      return admin.messaging().sendToDevice(tokens, payload).then(response => {
        // For each message check if there was an error.
        const tokensToRemove = [];
        response.results.forEach((result, index) => {
          const error = result.error;
          if (error) {
            console.error('Failure sending notification to', tokens[index], error);
            // Cleanup the tokens who are not registered anymore.
            if (error.code === 'messaging/invalid-registration-token' ||
                error.code === 'messaging/registration-token-not-registered') {
              tokensToRemove.push(allTokens.ref.child(tokens[index]).remove());
            }
          }
        });
        return Promise.all(tokensToRemove);
      });
    }
  });
});

I receive the log into Firebase console, but I don't see fcmTokens in the database and the device doesn't get the notification. what should I do? Thanks for the help.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
A. Inbar
  • 80
  • 14
  • "*I don't see fcmTokens in the database*" - Just to clarify, do you actually have the registration tokens for the devices (you saved them) or were you expecting that there is already an available value for this? – AL. Apr 13 '17 at 08:39
  • @AL. that what this part of my code: // Get the list of device tokens. should do but it doesn't. – A. Inbar Apr 13 '17 at 08:42
  • Could you post a sample of your db structure? – AL. Apr 13 '17 at 08:48
  • { "messageS" : { "-KUxeQy3g28bPPq5BZrQ" : { "message" : "שלום וברוכים הבאים לאפליקציה החדשה של בית הספר ״יגאל אלון״", "title" : "שלום" } } } – A. Inbar Apr 13 '17 at 08:49
  • 1
    The FCM tokens won't be in the database unless your applications write them there. Firebase does not automatically populate them for you. – Frank van Puffelen Apr 13 '17 at 08:51
  • @FrankvanPuffelen I think that's what my code does. can you help me? – A. Inbar Apr 13 '17 at 08:52
  • 1
    FCM tokens are generated on the device and are not automatically transported anywhere. You have to send it to your app server (or another storage like Firebase Database) in your own code that runs on the device. That's what the `sendRegistrationToServer()` in [this documentation page](https://firebase.google.com/docs/cloud-messaging/android/client#retrieve-the-current-registration-token) is meant to indicate. The code you shared runs on the Google servers and *reads* from the Firebase Database. There is no way it can determine the FCM tokens from that. – Frank van Puffelen Apr 13 '17 at 09:14
  • Have a look at my answer [here](https://stackoverflow.com/questions/53588736/storing-fcm-tokens-online/53589194#53589194) – Jan Feyen Dec 03 '18 at 08:33

0 Answers0