ionic-team / capacitor

Build cross-platform Native Progressive Web Apps for iOS, Android, and the Web ⚑️
https://capacitorjs.com
MIT License
11.45k stars 977 forks source link

bug: Notifications not showing #2907

Closed saricden closed 4 years ago

saricden commented 4 years ago

Bug Report

Capacitor Version

npx cap doctor output:

πŸ’Š   Capacitor Doctor  πŸ’Š 

Latest Dependencies:

  @capacitor/cli: 2.1.0

  @capacitor/core: 2.1.0

  @capacitor/android: 2.1.0

  @capacitor/electron: 2.1.0

  @capacitor/ios: 2.1.0

Installed Dependencies:

  @capacitor/ios not installed

  @capacitor/electron not installed

  @capacitor/cli 2.1.0

  @capacitor/core 2.1.0

  @capacitor/android 2.1.0

[success] Android looking great! πŸ‘Œ

Affected Platform(s)

Current Behavior

I'm using PushNotifiations.register() and PushNotifications.addListener('...') to register my app and listen for notifications. I'm sending notifications to the correct token from a Firebase function on my server. Now, whether the app is in the background or the foreground, the PushNotification.addListener('pushNotificationReceived') callback is triggered and no notification shows. Note that when I try to send a notification to the device token via the Firebase messaging test form it works as expected.

Expected Behavior

I would expect the 'pushNotificationReceived' callback to only fire when the app is in the foreground. I also expect a notification to show when the app is closed or in the background.

Sample Code or Sample Application Repo

Frontend code (React):

initNativeNotifications(username) {
    PushNotifications.register();

    PushNotifications.addListener('registration', async (token) => {
      console.log('got token', token);
      console.log('sending to server...');

      await db.doc(`/users/${username}`).update({
        messagingToken: token.value
      });

      console.log('done.');

      this.setState({
        notificationsEnabled: true
      });
    });

    PushNotifications.addListener('registrationError', (error) => {
      console.warn('Push registration failed', JSON.stringify(error));
    });

    PushNotifications.addListener('pushNotificationReceived', async (notification) => {
      console.log('Notification received!', notification);
      alert('Notification received!', notification);
    });

    PushNotifications.addListener('pushNotificationActionPerformed', (notification) => {
      console.log('Notification pressed!', notification);
    });
  }

Serverside code (Firebase function):

exports.sendTurnNotification = functions.firestore
  .document('/xxxxxxxx/{id}')
  .onUpdate((change, context) => {
    const data = change.after.data();
    const prevData = change.before.data();
    const {currentTurn} = data;
    const prevTurn = prevData.currentTurn;

    console.log('Sending notification to: ', currentTurn);

    return db.doc(`/users/${currentTurn}`).get()
      .then((doc) => {
        const userData = doc.data();

        if (userData.messagingToken) {
          const token = userData.messagingToken;

          console.log(`Sending notification to ${currentTurn}`, token);

          const message = {
            data: {
              title: "My App",
              body: `${prevTurn} just posted. You're up!`
            },
            token
          };
          return admin.messaging().send(message);
        }

        return false;
      })
      .then((response) => {
        console.log('Message send success', response);
      })
      .catch((error) => {
        console.log('Error sending message', error);
      });
  });

Reproduction Steps

Send a FCM to an Android app created w/ Capacitor & React, using the PushNotifications plugin. It's a bit of a complicated setup, but as far as I can tell the 'pushNotificationReceived' is being triggered when it shouldn't be, and a notification should be shown instead.

Other Technical Details

npm --version output:

(Yarn)

yarn --version
1.21.1

node --version output:

node --version
v12.0.0

pod --version output (iOS issues only):

n/a (Android only at this point).

Other Information

saricden commented 4 years ago

Hey guys, I solved it on my own! It was an error in my impementation.

I was sending an FCM w/ a data key, but I needed to send one with a notification key.

:shipit: :shipit: :shipit:

ionitron-bot[bot] commented 1 year ago

Thanks for the issue! This issue is being locked to prevent comments that are not relevant to the original issue. If this is still an issue with the latest version of Capacitor, please create a new issue and ensure the template is fully filled out.