React-native-firebase: 馃敟v6 onMessage is not fire when app in foreground

Created on 24 Dec 2019  路  40Comments  路  Source: invertase/react-native-firebase

Edit: I found in old document. The onMessage fire with data-only messages from FCM
Is this true in this version?


Issue

I installed successfuly react-native-firebase. I got FCM Token then send message from Firebase Console, and i got this issue. When app in background and killed mode, i got notification. But when in foreground the onMessage event doesn't fire.
My physical device : iPhone 6
iOS: 11.4




Project Files






Javascript

My code

componentDidMount = async () => {
    console.log(`fbApp.SDK_VERSION: ${fbApp.SDK_VERSION}`)
    //require Permission iOS
    let isRegister = fbMessaging.isRegisteredForRemoteNotifications
    console.log(`%c=====This isRegisteredForRemoteNotifications: ${isRegister}`, 'color: blue')
    if (!isRegister) {
      let regis = await fbMessaging.registerForRemoteNotifications()
      console.log(`=====This registerForRemoteNotifications: ${regis}`)
    }
    let hasPermission = await fbMessaging.hasPermission()
    console.log(`%chasPermission: ${hasPermission}`, 'color: blue')
    if (!hasPermission) {
      let grant = await fbMessaging.requestPermission()
      console.log(`%c=====This granted notification permission: ${grant}`, 'color: blue')
      if (!grant) {
        return
      }
    }

    const apnsToken = await fbMessaging.getAPNSToken()
    console.log('User APNS Token: ', apnsToken)

    const token = await fbMessaging.getToken()
    console.log('User FCM Token: ', token)
    if (token) {
      this.sendInfoToNotifServer(token)
    }
    this.props.updateToken(token)

    fbMessaging.onTokenRefresh(newtoken => {
      console.log('=====NEW TOKEN: ', newtoken)
      if (newtoken) {
        this.sendInfoToNotifServer(newtoken)
      }
      this.props.updateToken(newtoken)
    })

    this.unSubcribleOnMessage = fbMessaging.onMessage(mess => {
      console.log('=====onMesssage', mess)
    })

    fbMessaging.setBackgroundMessageHandler(mess => {
      console.log('=====onBackgroundMessage', mess)
    })

    this.unSubcribleOnDeleteMessage = fbMessaging.onDeletedMessages(() => {
      console.log('=====onDeleteMessage')
    })
  }

#### `package.json`:

    ....
    "@react-native-firebase/analytics": "^6.2.0",
    "@react-native-firebase/app": "^6.2.0",
    "@react-native-firebase/crashlytics": "^6.2.0",
    "@react-native-firebase/messaging": "^6.2.0",
    "@react-native-firebase/remote-config": "^6.2.0",
    ....
#### `firebase.json` for react-native-firebase v6:
# N/A
### iOS
Click To Expand

#### `ios/Podfile`: - [ ] I'm not using Pods - [x] I'm using Pods and my Podfile looks like:

# Pods for Sky500
  pod 'FBLazyVector', :path => "../node_modules/react-native/Libraries/FBLazyVector"
  pod 'FBReactNativeSpec', :path => "../node_modules/react-native/Libraries/FBReactNativeSpec"
  pod 'RCTRequired', :path => "../node_modules/react-native/Libraries/RCTRequired"
  pod 'RCTTypeSafety', :path => "../node_modules/react-native/Libraries/TypeSafety"
  pod 'React', :path => '../node_modules/react-native/'
  pod 'React-Core', :path => '../node_modules/react-native/'
  pod 'React-CoreModules', :path => '../node_modules/react-native/React/CoreModules'
  pod 'React-Core/DevSupport', :path => '../node_modules/react-native/'
  pod 'React-RCTActionSheet', :path => '../node_modules/react-native/Libraries/ActionSheetIOS'
  pod 'React-RCTAnimation', :path => '../node_modules/react-native/Libraries/NativeAnimation'
  pod 'React-RCTBlob', :path => '../node_modules/react-native/Libraries/Blob'
  pod 'React-RCTImage', :path => '../node_modules/react-native/Libraries/Image'
  pod 'React-RCTLinking', :path => '../node_modules/react-native/Libraries/LinkingIOS'
  pod 'React-RCTNetwork', :path => '../node_modules/react-native/Libraries/Network'
  pod 'React-RCTSettings', :path => '../node_modules/react-native/Libraries/Settings'
  pod 'React-RCTText', :path => '../node_modules/react-native/Libraries/Text'
  pod 'React-RCTVibration', :path => '../node_modules/react-native/Libraries/Vibration'
  pod 'React-Core/RCTWebSocket', :path => '../node_modules/react-native/'

  pod 'React-cxxreact', :path => '../node_modules/react-native/ReactCommon/cxxreact'
  pod 'React-jsi', :path => '../node_modules/react-native/ReactCommon/jsi'
  pod 'React-jsiexecutor', :path => '../node_modules/react-native/ReactCommon/jsiexecutor'
  pod 'React-jsinspector', :path => '../node_modules/react-native/ReactCommon/jsinspector'
  pod 'ReactCommon/jscallinvoker', :path => "../node_modules/react-native/ReactCommon"
  pod 'ReactCommon/turbomodule/core', :path => "../node_modules/react-native/ReactCommon"
  pod 'Yoga', :path => '../node_modules/react-native/ReactCommon/yoga'

  pod 'DoubleConversion', :podspec => '../node_modules/react-native/third-party-podspecs/DoubleConversion.podspec'
  pod 'glog', :podspec => '../node_modules/react-native/third-party-podspecs/glog.podspec'
  pod 'Folly', :podspec => '../node_modules/react-native/third-party-podspecs/Folly.podspec'

  pod 'GoogleIDFASupport', '~> 3.14.0'
#### `AppDelegate.m`:
/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

#import "AppDelegate.h"
@import Firebase;
#import <React/RCTBridge.h>
#import <React/RCTBundleURLProvider.h>
#import <React/RCTRootView.h>
#import "Orientation.h"
#import <CodePush/CodePush.h>

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
 if ([FIRApp defaultApp] == nil) {
     [FIRApp configure];
 }
  RCTBridge *bridge = [[RCTBridge alloc] initWithDelegate:self launchOptions:launchOptions];
  RCTRootView *rootView = [[RCTRootView alloc] initWithBridge:bridge
                                                   moduleName:@"Sky500"
                                            initialProperties:nil];
  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];
  // [Fabric with:@[[Crashlytics class]]];
  return YES;
}

- (NSURL *)sourceURLForBridge:(RCTBridge *)bridge
{
#if DEBUG
  return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];
#else
  return [CodePush bundleURL];
#endif
}

- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
  return [Orientation getOrientation];
}

@end


Environment

Click To Expand

**`react-native info` output:**

System:
    OS: macOS Mojave 10.14.5
    CPU: (4) x64 Intel(R) Core(TM) i5-3210M CPU @ 2.50GHz
    Memory: 136.41 MB / 8.00 GB
    Shell: 3.2.57 - /bin/bash
  Binaries:
    Node: 10.15.3 - /usr/local/bin/node
    Yarn: 1.15.2 - /usr/local/bin/yarn
    npm: 6.4.1 - /usr/local/bin/npm
  SDKs:
    iOS SDK:
      Platforms: iOS 13.2, DriverKit 19.0, macOS 10.15, tvOS 13.2, watchOS 6.1
    Android SDK:
      API Levels: 27, 28
      Build Tools: 27.0.3, 28.0.3
      System Images: android-28 | Google Play Intel x86 Atom
  IDEs:
    Android Studio: 3.3 AI-182.5107.16.33.5314842
    Xcode: 11.3/11C29 - /usr/bin/xcodebuild
  npmPackages:
    react: 16.9.0 => 16.9.0 
    react-native: 0.61.5 => 0.61.5 
  npmGlobalPackages:
    react-native-cli: 2.0.1
- **Platform that you're experiencing the issue on**: - [x] iOS - [ ] Android - [x] **iOS** but have not tested behavior on Android - [ ] **Android** but have not tested behavior on iOS - [ ] Both - **`react-native-firebase` version you're using that has this issue:** - `v6.2.0` - **`Firebase` module(s) you're using that has the issue:** - `Cloud Messaging` - **Are you using `TypeScript`?** - `N`




Think react-native-firebase is great? Please consider supporting all of the project maintainers and contributors by donating via our Open Collective where all contributors can submit expenses. [Learn More]

iOS Messaging

Most helpful comment

This is really frustrating/confusing for me. The documentation suggests that onMessage should fire when either in the foreground or background, but neither case works. There's also nothing in the documentation suggesting to modify AppDelegate.m to handle remote notifications. I'd really appreciate some clarity for a newbie - most of the suggestions here are way over my head.

  • How does one integrate FCM with react-native-push-notification? I don't see any tutorials out there. Especially when RNPN uses the APNS device token, which I don't know how translates to the FCM token. They don't seem to be the same.

  • What's this about notification, notification + data, etc? Are there supposed to be certain types of messages that will be intercepted by onMessage? How an I send those? I'm a total newbie to FCM so I need clear instructions.

I should also clarify that I'm trying to send messages from the FCM dashboard. Something on the old RNFB site suggests that the console can only send notifications, which is handled by a separate notification library and that the data-only notifications that onMessage receives only data-only messages, which cannot be sent by the firebase console anyway, only through cloud functions/etc. So this adds confusion to the mix.

For the time being I think I'm going to switch over to 5.x because that worked without this stress.

All 40 comments

the same thing happened to me as well, I think the notification module is not published yet by them.

the same thing happened to me as well, I think the notification module is not published yet by them.

i think if notification module is not published (they publish different package is Notifee but not OSS), so all message from firebase should be fire to onMessage event

After testing i confirm the event onMessage only fire with data-only messages from FCM so. Since this project doesn't support notification module, so onMessage should be fire everytime got message from Firebase with and without notification payload. Need someone fix this
Note: on Android working properly

Need someone fix this

"someone" is us. It's open source

Pull Requests happily accepted

@mikehardy i want to help but i don't know about native code. Can you add Need Help label to this issue

The same thing happen to me.

Data and Push notification received when in background.

When in Foreground Push notification doesn't work, but still can receive data (using onMessage)

The same thing happen to me.

Data and Push notification received when in background.

When in Foreground Push notification doesn't work, but still can receive data (using onMessage)

In foreground, notification won't be shown. You need push notification manual.
onMessage does not fire with combine Notification + Data payload or only Notification payload on IOS (but fire with Data payload only). Android always fire

@Salakar / @Ehesp what do you think of the idea that v6 should fire onMessage on any FCM (read as: mixed data+notification payloads) as opposed to current where on iOS it seems to fire only for data-only according to this?

The same thing happen to me.
Data and Push notification received when in background.
When in Foreground Push notification doesn't work, but still can receive data (using onMessage)

In foreground, notification won't be shown. You need push notification manual.
onMessage does not fire with combine Notification + Data payload or only Notification payload on IOS (but fire with Data payload only). Android always fire

I tested on Android EmulatorPixel_3_XL_API_28 and can confirm that it doesn't work in foreground (push notification with data). I need to use react-native-push-notification and @react-native-community/push-notification-ios (react-native-push-notification depends on this) just for fire local push notification :((

Hope react-native-firebase can help this as already support in version <=5

@maitrungduc1410 not going to happen - notifications is not a firebase core service (from google) so it won't exist going forward. Use data-only messages and a local solution (like react-native-push-notifications) as you've done

ReactNativeFirebaseMessagingService.java
onMessageReceived is doing nothing on notification only payload
The TODO is to broadcast intent when notifications module ready, but there wouldn't be notifications module

    // ----------------------
    //  NOTIFICATION Message
    // --------------------\/
    // with no data
    if (remoteMessage.getNotification() != null && remoteMessage.getData().size() == 0) {
      // TODO broadcast intent when notifications module ready
      return;
    }

RNFBv6 does not do notifications-anything. So a notification-only payload has no relation to react-native-firebase v6 and nothing should happen. Seems expected

RNFBv6 does not do notifications-anything. So a notification-only payload has no relation to react-native-firebase v6 and nothing should happen. Seems expected

can we use RNFBv6 to receive notification only FCM and show the notification ourself?

@kukuhyoniatmoko In my opinion you should use RNFBv6 to receive data-only FCM, then react-native-push-notification or similar to show the notification yourself. If you use notification payload or mixed data+notification payload, sometimes the firebase SDKs automatically do notification stuff (background, killed) sometimes you have to do it (foreground), which to me makes things hard to reason through. But it's should be possible to do notification-only + react-native-push-notifications and get all the cases handled well as well.

@kukuhyoniatmoko In my opinion you should use RNFBv6 to receive _data-only_ FCM, then react-native-push-notification or similar to show the notification yourself. If you use notification payload or mixed data+notification payload, sometimes the firebase SDKs automatically do notification stuff (background, killed) sometimes you have to do it (foreground), which to me makes things hard to reason through. But it's should be possible to do notification-only + react-native-push-notifications and get all the cases handled well as well.

Yes, on android firebase SDK we can receive notification only payload and then handle that ourself if fourground. So, I kind of expecting the same behavior on RNFBv6 onMessage
Thanks for your explanation @mikehardy

@mikehardy thanks for your work on this. I've scoured this repo for an answer and you've been very helpful. My argument for all notifications being received by onMessage is that I need to conditionally show notifications based on whether the app is in the foreground/killed (example, a chat app. you want notifications for new messages but not while you're in the app)

Looks like i'm going to have two requests per notification per chat message, (one to determine if app is closed and one to send the actual notification) which is not ideal but may work.

on android firebase SDK we can receive notification only payload and then handle that ourself if fourground. So, I kind of expecting the same behavior on RNFBv6 onMessage

We don't do anything here, if you send an FCM payload with a notification object the SDK will show a notification. That's built in functionality - albeit you can't handle actions and the documentation is lacking.

I've also got onMessage working in the foreground here on v6.

on android firebase SDK we can receive notification only payload and then handle that ourself if fourground. So, I kind of expecting the same behavior on RNFBv6 onMessage

We don't do anything here, if you send an FCM payload with a message object the SDK will show a notification. That's built in functionality - albeit you can't handle actions and the documentation is lacking.

I've also got onMessage working in the foreground here on v6.

@Ehesp: As above my comment, on IOS onMessage event does not working in the foreground on v6. Should we fix this?

I've tested push both on background and foreground with iOS and Android and everything works. To make it work on iOS foreground I had to sent the push through APNs as a silent notification and not through the FCM connection server. I hope it is useful.

I've tested push both on background and foreground with iOS and Android and everything works. To make it work on iOS foreground I had to sent the push through APNs as a silent notification and not through the FCM connection server. I hope it is useful.

i think the onMessage should be fire not only silent notification but also mix payload

This is really frustrating/confusing for me. The documentation suggests that onMessage should fire when either in the foreground or background, but neither case works. There's also nothing in the documentation suggesting to modify AppDelegate.m to handle remote notifications. I'd really appreciate some clarity for a newbie - most of the suggestions here are way over my head.

  • How does one integrate FCM with react-native-push-notification? I don't see any tutorials out there. Especially when RNPN uses the APNS device token, which I don't know how translates to the FCM token. They don't seem to be the same.

  • What's this about notification, notification + data, etc? Are there supposed to be certain types of messages that will be intercepted by onMessage? How an I send those? I'm a total newbie to FCM so I need clear instructions.

I should also clarify that I'm trying to send messages from the FCM dashboard. Something on the old RNFB site suggests that the console can only send notifications, which is handled by a separate notification library and that the data-only notifications that onMessage receives only data-only messages, which cannot be sent by the firebase console anyway, only through cloud functions/etc. So this adds confusion to the mix.

For the time being I think I'm going to switch over to 5.x because that worked without this stress.

Running on IOS 13.3. For me sent from the console. The notification shows without hitting the messaging().setBackgroundMessageHandler();.
Clicking on notification, using 'react-native-notifications' I can able to get the notification data completely.
when the app is opened onMessage is not triggered.
Am I missing anything? Followed all the steps from the doc but still, the message is not received in device onMessage.
Do I need to set any extra data while sending the message from the backend or console?

As above my comment, on IOS onMessage event does not working in the foreground on v6. Should we fix this?

I have an example app locally with it working in both situations. We're overhauling the docs and messaging will be getting my main focus https://github.com/invertase/react-native-firebase/issues/3217.

@tmaly1980 your frustrations are welcome! Honestly, there is a LOT going on with messaging under the hood and it's confusing to us too. Hopefully in the next few weeks we'll have some more docs with full guides in place.

I just want to ask in v6 the event (listener) "notification when open" is this been removed? if I click the FCM message on my notification bar, it will not receive any data for that notification? I'm so confused on the cloud messaging firebase.messaging().setBackgroundMessageHandler because it's not working on my part

Thanks,

UPDATED

I just installed the react-native-push-notification , this solves my issue from background notification. Also, I notice on iOS the only thing you can test the FCM is through actual device with RELEASE version built. It will not work in DEBUG version of the app and it gives me an error even I'm using an actual device (not via simulator).

any updates?

Does onMessage work in previous versions?

Does onMessage work in previous versions?

Yes, v5 works like a charm.

As above my comment, on IOS onMessage event does not working in the foreground on v6. Should we fix this?

I have an example app locally with it working in both situations. We're overhauling the docs and messaging will be getting my main focus #3217.

@tmaly1980 your frustrations are welcome! Honestly, there is a LOT going on with messaging under the hood and it's confusing to us too. Hopefully in the next few weeks we'll have some more docs with full guides in place.

@Ehesp
Can you give link working sample ? or suggestions to make it working?

Just a heads up, myself and @Salakar just spent the entire day digging into the depths of Android FCM. We're going to release an update to v6 at some point (will link PR when it's up), however in a nutshell this will be the update:

  • Rename of registerForRemoteNotifications to registerDeviceForRemoteMessages. This will be a deprecation and will be removed in v7. Nothing internally is changing, however the current wording is just totally confusing.
  • The background handler will be ALWAYS set, and if you dont provide a handler to setBackgroundMessageHandler it'll throw a better/custom warning (e.g. not a React Native one).
  • onMessage will work for data-only, notification-only AND data-notification messages. Currently it only works for data-only.
  • setBackgroundMessageHandler will now work when the app is both fully quit and backgrounded, for data-only, notification-only AND data-notification messages.

    • took a while to figure out to handle this one...

  • We're implementing both getInitialNotification & onNotificationOpenedApp into the messaging module. This won't require any native changes from users.
  • If a message is sent with a notification payload, it'll be included within the RemoteMessage object passed around.

It's worth noting that a visible notification will only be displayed on the device when the apps is quit or in the background. This is controlled fully by Android. If you wish to display one in the Foreground, or anything other than a title/body/image, you need to use a 3rd party library.

iOS will be getting reviewed next to figure out these things.

Okay so Android seems to be working (needs more testing etc), so I'll move onto iOS next.

https://github.com/invertase/react-native-firebase/pull/3309

Hello @Ehesp will you be able to tell us a date where the version 7 would be released?

We are waiting to have this since we have upgraded Crashlytics to v6, unfortunately, all our firbase notification breaks since we have been using version 5 for that.

we also have the same problems of having v6 for notifications :(

Android updates are in 6.4.0-rc0 which you can try out now. I'm currently working on ios changes to match.

Android updates are in 6.4.0-rc0 which you can try out now. I'm currently working on ios changes to match.

Perfects and thanks, maybe a rough date of ios release :) ?

Should be within a week, just need to get my head around a few things first... not a fan of iOS dev :(

Should be within a week, just need to get my head around a few things first... not a fan of iOS dev :(

hahahha...Thanks buddy for the update!

@Ehesp
in 6.4.0-rc, IOS onMessage event can work in the foreground on v6? in 6.3.3, I cannot received messages on onMessage.

Just android, working on ios now.

Hey all 馃憢 There's a draft PR available which fixes this issue and others, please check it out: https://github.com/invertase/react-native-firebase/pull/3339

We'll be doing a RC release once a few more things are implemented.

Hi, I have build release android to try react-native firebase V6 and using notifee to display notifcation, background and foreground working well in debug, but in release, just background is working, while foreground is failed.
Someone can help me? Stuck on this problem many days

Hi there @programmer-RN I strongly recommend you open an issue with Notifee, as one of the things the Notifee license pays for is support. Honestly that's really the whole point of the fee, reliable support :-). Foreground notifications is a notifee function not a react-native-firebase thing

Was this page helpful?
0 / 5 - 0 ratings