Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Notifications triggers onMessage instead of onNotification #1900

Closed
2 of 27 tasks
fredrikp opened this issue Feb 14, 2019 · 32 comments
Closed
2 of 27 tasks

Notifications triggers onMessage instead of onNotification #1900

fredrikp opened this issue Feb 14, 2019 · 32 comments

Comments

@fredrikp
Copy link

Issue

When sending push notifications with only the "notification" field with "title" and "body" inside, I would expect the notification to be automatically displayed and onNotification to be triggered. Instead nothing is displayed and onMessage is triggered with an empty "data" object. I have only tried iOS so far, not Android yet.

Project Files

iOS

ios/Podfile:

  • I'm not using Pods
  • [] I'm using Pods and my Podfile looks like:
# N/A

AppDelegate.m:

#import "AppDelegate.h"
#import <React/RCTBundleURLProvider.h>
#import <React/RCTRootView.h>
#import "Firebase.h"
#import "RNFirebaseNotifications.h"
#import "RNFirebaseMessaging.h"

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  NSURL *jsCodeLocation;
	
	[FIRApp configure];
	[RNFirebaseNotifications configure];
	
	NSDictionary* infoDict = [[NSBundle mainBundle] infoDictionary];
	NSString *environment = [infoDict valueForKey:@"Environment"];
	NSDictionary *initialProps = @{@"environment" : environment};
	jsCodeLocation = [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];
  RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
                                                      moduleName:@"GXBooking"
                                               initialProperties:initialProps
                                                   launchOptions:launchOptions];
  rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f green:1.0f blue:1.0f alpha:1];

  self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
  UIViewController *rootViewController = [UIViewController new];
  rootViewController.view = rootView;
  self.window.rootViewController = rootViewController;
  [self.window makeKeyAndVisible];

  return YES;
}

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
	[[RNFirebaseNotifications instance] didReceiveLocalNotification:notification];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(nonnull NSDictionary *)userInfo
fetchCompletionHandler:(nonnull void (^)(UIBackgroundFetchResult))completionHandler{
	[[RNFirebaseNotifications instance] didReceiveRemoteNotification:userInfo fetchCompletionHandler:completionHandler];
}

- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings {
	[[RNFirebaseMessaging instance] didRegisterUserNotificationSettings:notificationSettings];
}

@end

Android

android/build.gradle:

// N/A

android/app/build.gradle:

// N/A

android/settings.gradle:

// N/A

MainApplication.java:

// N/A

AndroidManifest.xml:

<!-- N/A -->

Environment

  • Platform that you're experiencing the issue on:
    • iOS
    • Android
    • [x ] iOS but have not tested behavior on Android
    • Android but have not tested behavior on iOS
    • Both
  • If known, the version of the platform are you experiencing the issue on:
    • iOS 12.1.4
  • Operating System:
    • [x ] MacOS, version: 10.14.3
    • Windows, version: N/A
    • Other, please specify: N/A
  • Build Tools:
    • Xcode 10.1
  • React Native version:
    • 0.57.8
  • React Native Firebase library version:
    • 5.2.2
  • Firebase module(s) you're using that has the issue:
    • [] N/A
    • Authentication
    • Analytics
    • Cloud Firestore
    • [x ] Cloud Messaging (FCM)
    • Crashlytics
    • Dynamic Links
    • Functions Callable
    • In App Messaging
    • Indexing
    • Invites
    • Instance ID
    • ML Kit
    • [x ] Notifications
    • Performance Monitoring
    • Realtime Database
    • Remote Config
    • Storage
  • Are you using TypeScript?
    • [x ] No
    • Yes, version: N/A
  • Are you using Expo, e.g. ExpoKit?
    • No
    • Yes, I've not ejected
    • Yes, but I have ejected to ExpoKit
    • Yes, but I have ejected to vanilla React Native
    • Expo version: N/A

I have verified that the app has asked for permission and that a token exists. This is the code that I am using in React Native to see which triggers are triggered:

        this.notificationListener = firebase.notifications().onNotification(notification => {
            console.log('onNotification', notification);
        });

        this.messageListener = firebase.messaging().onMessage(message => {
            console.log('onMessage', message);
        });

This is the way I send a notification - I have also tried to send from the Firebase console with the same effect, only onMessage is triggered:

curl https://fcm.googleapis.com/fcm/send -X POST \
--header "Authorization: key=AAAAC---actual-key-removed---TZHqW" \
--Header "Content-Type: application/json" \
-d '
{
   "to": "fBSnq---actual-device-id-removed---TZHqW"
   "notification":{
     "title":"Notification title",
     "body":"Notification body",
   },
}'

Think react-native-firebase is great? Please consider supporting the project with any of the below:

@fredrikp
Copy link
Author

Also, Firebase SDK version is 5.16.0. Libraries from Analytics and Messaging have been added to the app.

@nyenye
Copy link

nyenye commented Feb 24, 2019

This happens to me too as of today with iOS. The most that I could get to work is onMessage, and right now not even onMessage triggers.

On Android works as expected tho.

@yjacobowitz
Copy link

This happens to me as well in android - only onMessage works for me, notification events don't

@nyenye
Copy link

nyenye commented Feb 25, 2019

Yesterday I could solve the issue for iOS and I found out that this was missing in the Firebase Console (https://firebase.google.com/docs/cloud-messaging/ios/first-message#upload_your_apns_authentication_key)

@yjacobowitz - For me Android gave me no trouble at all. Have you followed the setup process for Notifications too for react-native-firebase? (https://rnfirebase.io/docs/v5.x.x/notifications/android)

@yjacobowitz
Copy link

Yes I realized now I missed one step and it works, is there a way to know when the notification is received (in background/closed) even if the user doesn't open it?

@nyenye
Copy link

nyenye commented Feb 25, 2019

I think that the only time you have to handle notifications is on the foreground. On the background you have the option to send messages: (Android only) https://rnfirebase.io/docs/v5.x.x/messaging/receiving-messages#4)-(Optional)(Android-only)-Listen-for-FCM-messages-in-the-background

Hope it helps.

@fabiodamasceno
Copy link

Messages works without APN's configuration, did you checked your apple certificates? Another aspect you can test is reconfigure FCM in console panel, this worked for me.

Hugs,

@stale
Copy link

stale bot commented Apr 14, 2019

Hello 👋, this issue has been automatically marked as stale because it has not had activity for quite some time. Has the issue been fixed, or does it still require the community's attention? This issue may be closed if no further activity occurs. Thank you for your contributions.

@stale stale bot added the Type: Stale Issue has become stale - automatically added by Stale bot label Apr 14, 2019
@luatvudinh
Copy link

+1.
Please give me solution for it. With ios when I push notification by pusher (https://github.com/noodlewerk/NWPusher), it worked perfectly. But I prefer to use firebase to push more platforms in once (web, android, ios). I do added APNs Authentication Key into my Firebase ios app configuration and this is my function on my server (python):

def push_ntf_to_topic(title, message):
    aps = messaging.Aps(alert=ApsAlert(title = title, body = message))
    payload = messaging.APNSPayload(aps)
    mes = messaging.Message(
        notification = messaging.Notification(
            title = title,
            body = message
        ),
        token=token,
        apns = messaging.APNSConfig(payload=payload)
    )

    res = messaging.send(mes)

My ios app could be received message but not push notification (message included apns such above).
Thanks for reading.

@stale stale bot removed the Type: Stale Issue has become stale - automatically added by Stale bot label Apr 24, 2019
@nirojan0930
Copy link

Hi,
I'm also facing the same issue on iOS, but in android it's working properly. For same notification sending from firebase console onNotification is triggering in android but onMessage is triggering in iOS. Have you found any solutions to this?

@mi-mazouz
Copy link

any update? I have the same issue on IOS onNotification and onNotificationDisplayed are not triggered.

@mikehardy
Copy link
Collaborator

@mi-mazouz what versions of everything? react-native-firebase 5.3.1 works with pods 5.20.2, or are you not using pods? which versions of ios does it happen on? There's a reason for the new issue template :-)

@mi-mazouz
Copy link

mi-mazouz commented May 23, 2019

@mikehardy Sorry I didn't give you any information, so I use the react-native-firebase latest version (5.3.1), pod and the firebase messing version is pod 'Firebase/Messaging', '~> 5.20.2'. I'm trying it on the latest ios simulator version so 12.2.

my code looks like:

import React, { Component } from 'react'
import firebase from 'react-native-firebase';
import { Text, View } from 'react-native'

class App extends Component {
  public async componentDidMount() {
    this.handleFirebaseMessaging();
  }

  public componentWillUnmount() {
    this.notificationDisplayedListener();
    this.notificationListener()
  }

  public async handleFirebaseMessaging() {
    const fbmEnabled = await firebase.messaging().hasPermission();

    if (fbmEnabled) {
      this.handleFirebaseMessagingToken();
    } else {
      await firebase.messaging().requestPermission();
      await this.handleFirebaseMessagingToken();
    }
    this.handleFirebaseMessagingListeners();
  }

  public async handleFirebaseMessagingToken() {
    const storedToken = await get('fbcmToken');
    const fbcmToken = await firebase.messaging().getToken();

    console.log('FIREBASE TOKEN:', fbcmToken);
    if (!storedToken || storedToken !== fbcmToken) {
      await store('fbcmToken', fbcmToken);
      if (storedToken !== fbcmToken) {
        console.log(
          'You have the wrong token version stored'
        );
      }
    }
  }

  public handleFirebaseMessagingListeners() {
    this.messageListener = firebase.messaging().onMessage(message => {
      // process data message
      console.log('ON MESSAGE:', JSON.stringify(message));
    });

    this.notificationDisplayedListener = firebase
      .notifications()
      .onNotificationDisplayed(notification => {
        console.log('ON NOTIFICATION DISPLAYED');
      });

    this.notificationListener = firebase
      .notifications()
      .onNotification(notification => {
        console.log('ON NOTIFICATION');
      });
  }

  public render() {
    return (
        <View><Text>Hello world</Text>
    );
  }
}

export default App;

onMessage is the only listener triggered when I send a notification via firebase cloud messaging even in background or when the app is closed

@mikehardy
Copy link
Collaborator

that is certainly more to work with :-), I am literally testing these exact things in my app now, I'll let you know what I see

@mi-mazouz
Copy link

@mikehardy any news?

@mikehardy
Copy link
Collaborator

mikehardy commented May 24, 2019

At the moment I have multiple failures, and I think the best thing is to create a small repo to cleanly reproduce them. I'm not seeing onNotificationOpened consistently, getInitialNotification isn't populating correctly, etc. And this library in general has a mountain of issues related to notifications and messaging that are all subtle because setups are so different - seems like each thing is working for someone, but everyone has a problem with something else... So first I just want to prove (to myself, but also demonstrably to anyone) that it is possible and/or open issues if not. Not a concrete result for you, sorry.

@mi-mazouz
Copy link

I'll open a new issue

@Nerogee
Copy link

Nerogee commented Jun 3, 2019

May my case provide some cues.
In my app, I called firebase.messaging().deleteToken() and firebase.messaging().getToken() each time a user login. As long as I keep my app open, i conduct as many time as I wish to login and logout a user , which successfully gives me a new fcm token that is just working fine. But it stops working after I close my app and reopen again. At this point of time, the existing fcm token still works as long as I don't conduct firebase.messaging().deleteToken() and firebase.messaging().getToken() for a new token again.

FOUR weird things,

  1. after close and reopen the app, and the first time to have a login which I expect it returns a new fcm token but it does not. It give me the same token as I had before closing the app.
  2. Try logout and login again, it now returns a new fcm token.
  3. This new fcm token can be used to push notification with SUCCESSFUL return. BUT, it ONLY triggers the firebase.messaging().onMessage(), but I would expect it trigger the firebase.notifications().onNotification
  4. If I go to IOS settings to turn off notification permission and back to my app to toggle notification permission (this is app feature itself which is to allow user to control if he wants to receive notification or not). The feature check system permission first and a button in popup that can redirect user to system settings if permission is not granted, which is exactly the case I want to test. When at system permission screen, enable the notification. Then back to my app, enable the (In app) notification, this time there won't have permission popup as I just enable it at system settings. OK. It now starts to work normal, UNTIL I close my app and conduct another logout and login. (back to step 1 again)

@filipef101
Copy link

Hey, so I have the same issue when using a third party services, example: http://pushtry.com/ , and what is triggered is firebase.messaging().onMessage

Might this be related to the native setup?

Or might it be the standard behavior? if so how should this be dealt with?

With firebase-admin "firebase.messaging().sendToDevice(fcmToken, notification, options)" on my back-end does send the native notification

Also using fcm or gcm mode it also triggers on iOS the onMessage.
Thanks

@mikehardy
Copy link
Collaborator

For those having notification listener issues - if you integrated react-native-splash-screen following the most popular tutorial that has you use a separate LaunchActivity, that's the root cause here. I have all my listeners working correctly on android now following the code I pasted in the related issue here: crazycodeboy/react-native-splash-screen#289 - I believe iOS is working as well so I'm not aware of any more issues related to the module functioning. Its easy for project code to be wrong or for your messages to be not correct though - it is very hard to get these things correct.

@mikehardy
Copy link
Collaborator

I believe messaging and notifications (please be careful! In Firebase-land they mean different things - messaging is cloud stuff, notification is device pop-up stuff) are working in the general case, i.e., the original issue here. If you are still having problems please please please open a new issue and follow the template

@jnrana
Copy link

jnrana commented Sep 9, 2019

I am facing same issue.

When i send notification on iOS it triggers onMessage theres is no activity in onNotification event and no banner pops up.
Same thing works fine on android though.

react-native: 0.59.4
react-native-firebase: 5.5.6

podfile

  pod 'Firebase/Core'
  pod 'Firebase/Messaging'

APNs certificates added on firebase settings as well. Nothing seems to work.

@srknzcn
Copy link

srknzcn commented Sep 10, 2019

i'm facing same issue and i'm walking around until 5 hours. I'm trying same code on android and onNotification listener works but on iOS only onMessage listener work. This make me crazy!! Finally i've tried on real iOS device and everything works... If you trying launch app on ios simulator for foreground notifications, please try on real device.

@ghost
Copy link

ghost commented Sep 30, 2019

@srknzcn push notifications does not work on ios simulator. Apple does not support it.

@bishwajeet-billme
Copy link

Hi,
I'm also facing the same issue on iOS, but in android it's working properly. For same notification sending from firebase console onNotification is triggering in android but onMessage is triggering in iOS. Have you found any solutions to this?

yes same issue, I am already facing is there any genuine solution to fix this problem.

@batmaster
Copy link

batmaster commented Nov 25, 2019

iOS onNotification() still not triggered. Instead onMessage() is. Then, iOS can receive notification only if the app is opened.

I've tried to reconfigure APNs Authentication Key and APNs Certificates and even remove them from FCM console, the result is same.

Note that I tried on real iPhones which ever worked some days ago.

@blazk0
Copy link

blazk0 commented Nov 28, 2019

I am having the same issue as well.
Notification are working as expected on android but on ios onMessage is triggered instead .
Which is weird because it was working on both platforms about 2 weeks ago.

@blazk0
Copy link

blazk0 commented Nov 30, 2019

@batmaster have your figured out what the problem is ?
onNotification was working fine on both platforms some time ago
Now it does only for android and for ios onMessage is triggered intead.

@LPranulis
Copy link

Same issue. (About iOS) Yesterday, when I was setting a project for iOS, I had this issue, but I resolved it by uploading APNS Auth token to FCM Console. Notifications were working on every scenario. But today, I don't know why it only triggers onMessage again...

@fastmanu
Copy link

Same here :|

@iocuydi
Copy link

iocuydi commented Jan 10, 2020

I struggled for hours with this issue after my (iOS) push notifications inexplicably stopped working, then finally solved it.

First, have a look here: #1203 (comment)
and make sure you follow all of these steps carefully.

The extra step that made it work for me was adding

[UNUserNotificationCenter currentNotificationCenter] setDelegate:self];

as the very last line before "return YES;" in didFinishLaunchingWithOptions.

Note that I also had the block of extra code above (if ([UNUserNotificationCenter class] != nil) {....), but it did not work without adding that last line at the end of the method.

@amon-shadow
Copy link

amon-shadow commented Jan 17, 2020

resolved by
#2192 (comment)

thanks a lot

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests