React-native-firebase: firebase.notifications().onNotificationOpened not working

Created on 28 May 2018  ·  52Comments  ·  Source: invertase/react-native-firebase

firebase.notifications().getInitialNotification() working when app closed, but firebase.notifications().onNotificationOpened not working when App in Foreground and background
IOS: 9.1 (13B143)
docs: https://rnfirebase.io/docs/v4.2.x/notifications/receiving-notifications

  componentDidMount(){
    firebase.notifications().getInitialNotification()
      .then((notificationOpen: NotificationOpen) => {
        if (notificationOpen) {
          if (checkVariableExist(this.props.screenProps)) {
            this.props.screenProps.navigate("NotificationsScreen");
          } else {
            this.props.navigation.navigate("NotificationsScreen");
          }
        }
      });
    this.notificationOpenedListener = firebase.notifications().onNotificationOpened((notificationOpen: NotificationOpen) => {
      if(notificationOpen) {
        if (checkVariableExist(this.props.screenProps)) {
          this.props.screenProps.navigate("NotificationsScreen");
        } else {
          this.props.navigation.navigate("NotificationsScreen");
        }
      }
    });
  }

  componentWillUnmount() {
    this.notificationOpenedListener();
  }
Notifications General Needs Triage Bug Android iOS

Most helpful comment

I solved this with the following files

NotificationListeners.js

import firebase from 'react-native-firebase';
import { ts } from './FirebaseHelpers';
// https://rnfirebase.io/docs/v5.x.x/notifications/introduction

export const notificationDisplayedListener = () =>
  // app in foreground
  firebase.notifications().onNotificationDisplayed(notification => {
    console.log('onNotificationDisplayed');
    console.log(notification);
  });

export const notificationListener = () =>
  // app in foreground
  firebase.notifications().onNotification(notification => {
    console.log('notificationListener');
    console.log(notification);

    const localNotification = new firebase.notifications.Notification({
      sound: 'default',
      show_in_foreground: true,
      show_in_background: true,
    })
      .setNotificationId(notification.notificationId)
      .setTitle(notification.title)
      .setSubtitle(notification.subtitle)
      .setBody(notification.body)
      .setData(notification.data)
      .android.setChannelId('General')
      .android.setSmallIcon('@mipmap/ic_notification')
      .android.setColor('#F2C94C')
      .android.setPriority(firebase.notifications.Android.Priority.High);

    firebase.notifications().displayNotification(localNotification);
    console.log('displayed');
    firebase.notifications().removeDeliveredNotification(localNotification.notificationId);
  });

export const notificationOpenedListener = () =>
  // app in background
  firebase.notifications().onNotificationOpened(notificationOpen => {
    console.log('notificationOpenedListener');
    console.log(notificationOpen);
    const { action, notification } = notificationOpen;
    firebase.notifications().removeDeliveredNotification(notification.notificationId);
    console.log('OPEN:', notification);
  });

export const notificationTokenListener = userId =>
  // listens for changes to the user's notification token and updates database upon change
  firebase.messaging().onTokenRefresh(notificationToken => {
    console.log('notificationTokenListener');
    console.log(notificationToken);

    return firebase
      .firestore()
      .collection('users')
      .doc(userId)
      .update({ pushToken: notificationToken, updatedAt: ts })
      .then(ref => {
        console.log('savePushToken success');
      })
      .catch(e => {
        console.error(e);
      });
  });

SplashActivity.java

package com.daviswhitehead.shayr.android;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

public class SplashActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Intent intent = new Intent(this, MainActivity.class);

        // Pass along FCM messages/notifications etc.
        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            intent.putExtras(extras);
        }

        startActivity(intent);
        finish();
    }
}

AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.daviswhitehead.shayr.android"
    xmlns:tools="http://schemas.android.com/tools" >

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <uses-permission android:name="android.permission.VIBRATE" />

    <application
        android:name=".MainApplication"
        android:label="@string/APP_NAME"
        android:icon="@mipmap/ic_launcher"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:allowBackup="false"
        android:theme="@style/AppTheme"
        tools:replace="android:label">

        <activity
            android:name=".SplashActivity"
            android:theme="@style/SplashTheme"
            android:label="@string/APP_NAME"
            android:launchMode="singleTask" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity
            android:name=".MainActivity"
            android:label="@string/APP_NAME"
            android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
            android:windowSoftInputMode="adjustResize"
            android:exported="true"
            android:launchMode="singleTask" >
        </activity>

        <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id"/>

        <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />

        <!-- NOTIFICATION DEFAULTS -->
        <meta-data
            android:name="com.google.firebase.messaging.default_notification_channel_id"
            android:value="@string/default_notification_channel_id"/>

        <!-- Set custom default icon. This is used when no icon is set for incoming notification messages.
            See README(https://goo.gl/l4GJaQ) for more. -->
        <meta-data
            android:name="com.google.firebase.messaging.default_notification_icon"
            android:resource="@mipmap/ic_notification" />
            <!-- android:resource="@drawable/ic_notification" /> -->
        <!-- Set color used with incoming notification messages. This is used when no color is set for the incoming
            notification message. See README(https://goo.gl/6BKBk7) for more. -->
        <meta-data
            android:name="com.google.firebase.messaging.default_notification_color"
            android:resource="@color/yellow" />

        <!-- SHARE ACTIVITY -->
        <activity
            android:noHistory="true"
            android:name=".share.ShareActivity"
            android:configChanges="orientation"
            android:label="@string/TITLE_ACTIVITY_SHARE"
            android:screenOrientation="portrait"
            android:theme="@style/Theme.Share.Transparent" >
            <intent-filter>
                <action android:name="android.intent.action.SEND" />
                <category android:name="android.intent.category.DEFAULT" />
                //  for sharing links include
                <data android:mimeType="text/plain" />
                //  for sharing photos include
                <data android:mimeType="image/*" />
            </intent-filter>
        </activity>

        <!-- FABRIC -->
        <meta-data
            android:name="io.fabric.ApiKey"
            android:value="c12e5c4bb8cd8ca855a8ada44fa3fde413006659" />

        <!-- REACT-NATIVE-FIREBASE NOTIFICATIONS -->
        <service android:name="io.invertase.firebase.messaging.RNFirebaseMessagingService">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>

        <service android:name="io.invertase.firebase.messaging.RNFirebaseInstanceIdService">
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
            </intent-filter>
        </service>

        <!-- SCHEDULED NOTIFICATIONS -->
        <receiver android:name="io.invertase.firebase.notifications.RNFirebaseNotificationReceiver"/>
        <receiver android:enabled="true" android:exported="true"  android:name="io.invertase.firebase.notifications.RNFirebaseNotificationsRebootReceiver">
            <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED"/>
            <action android:name="android.intent.action.QUICKBOOT_POWERON"/>
            <action android:name="com.htc.intent.action.QUICKBOOT_POWERON"/>
            <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </receiver>
    </application>
</manifest>

All 52 comments

Did you fix this? I have the same problem.

Notification triggers onNotification when it should trigger onNotificationOpened..

I am developing on ios.

@hoanghapo I am also facing same issue, its not getting triggered when user clicks on the notification. How did you fix it?

@hoanghapo I am doing the same thing code is also same as you shared but i am not getting any issue on IOS but on android the things are working fine when in debug mode but nothing happens when i test using release apk. any help please.?

@SkyTreasure I was having issues with the iOS notification listeners as well on iOS 11.

@Salakar Fixed the issue by commenting out line 77 & 95 from didReceiveLocalNotification in the RNFirebaseNotifications.m:
77: //if ([self isIOS89]) {
95: //}

Hi I am experiencing the same. Works fine on android. But no luck on iOS. @projectpublius 's solution works.

Environment
Application Target Platform:
iOS 11.2

Development Operating System:
macOS 10.12.6

Build Tools:
Bazel

React Native version:
0.55.4

React Native Firebase Version:
4.3.8

Firebase Module:
Notification, Message

Are you using typescript?
no

Same issue, I am on rnfirebase version 4.3.8. Getting a callback one in 50 times randomly

@chrisbianca it'd be great if you could have a look

Also experiencing an issue with this, any idea if this is a confirmed bug?

I have an issue "Sending notifications_notification_opened with no listeners registered."
"ios": 12
"react-native-firebase": "5.0.0-rc2"
"react-native": "0.57.0"
any ideas?

For anyone else stumbling across this issue:

Making a duplicated issue will not help, you're only making it harder for maintainers to actually collate and discuss the issue towards a resolution. It's the complete opposite of helpful. 😪

I ended up figuring out what was going wrong on my side. It was fairly specific to my application but maybe it will help others:

I ended up having two separate issues:

1) To begin, I had the following in set in didFinishLaunchingWithOptions
[UNUserNotificationCenter currentNotificationCenter].delegate = self;

which overrides the ReactNativeFirebase specific behavior of listening
to notification open and pushing this information accross the bridge to
be handled by JS. You can see this behavior here:

https://github.com/invertase/react-native-firebase/blob/master/ios/RNFirebase/notifications/RNFirebaseNotifications.m#L203-L215

In particular, I believe this arose from following the FirebaseIOS setup
docs found here: https://github.com/firebase/quickstart-ios/blob/master/messaging/MessagingExample/AppDelegate.m

Which is an example of how to set up Firebase on Ios and handle these
callbacks your self manually. This type of setup is not needed if you
are using ReactNativeFirebase as this will be handled by the bridged
module so that it can intercept these messages and pass them to JS.

2) We are using the IntercomIOS library ad Intercom react-native to send push notifications from our application to users when we respond to them from Intercom.

If you follow the Intercom onboarding, you will add the following to your AppDeligate.m

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    [Intercom setDeviceToken:deviceToken];
}

Its a bit hard to find, but this call will actually swizzle the public methods
in UIApplicationDelegate
.

In particular, this overrides the handling of FirebaseReactNative of notification open actions.


TLDR; Make sure that you are not overridding public methods in UIApplicationDelegate

I have experienced this problem also on Android, getInitialNotification's payload is not consistent, sometimes it returns the notificationOpenpayload, and most of the time it returns null.

I have no way to identify if the app is opened via a notification tap. But I temporarily solved my problem by using this hack, using AppState and AsyncStorage.

  1. On your headlessTask handler, for example mine named firebaseBackgroundTask.js.
// @flow
import firebase from "react-native-firebase";
import { AppState, AsyncStorage } from "react-native";
import type { RemoteMessage, NotificationOpen } from "react-native-firebase";

export default async (message: RemoteMessage) => { 
    const currentAppState = AppState.currentState;

    // listen for app state change, then save the message data using AsyncStorage
    AppState.addEventListener("change", nextAppstate => {
        if(currentAppState === "active" && nextAppState === "uninitialized") {
            // I named the item key `FCM.BG_MESSAGE` but you can name it what you want.
            // Then, serialise the data to JSON, because AsyncStorage only allow strings as value
            AsyncStorage.setItem("FCM.BG_MESSAGE", JSON.stringify(message.data));
        }
    });

    // display your notification here
};
  1. On your root component's(mine is on App.js) componentDidMount lifecycle hook, add this
export default class extends React.PureComponent<*> {
    componentDidMount() {
         AsyncStorage.getItem("FCM.BG_MESSAGE")
             .then(json => {
                 const data = jsonData ? JSON.parse(jsonData) : false;
                 console.log(data);
                 // then do navigation, or whatever you want to the data.
             }).catch(e => console.log(e));
    }
}

Hope it helps someone! Cheers! 😄

any updates on this?

still a bug....

I am facing the issue of push notification. When I send from firebase console the application crash. (RN 0.57.0 , RN Firebase ^5.1.0)

@Salakar What should we be expecting with regards to this? I understand you guys have a ton of things to get to, so I'm just wondering if you guys think you'll have a fix for this soon or if I should devote extra time to finding a fix or switching libraries? I just don't wanna put in a ton of effort only to find you guys coming out with a solution days later.

@kevinEsherick Hey have you found a solutions maybe?? thanks!

@artiumGlobalbit I have not. I was hoping for just a brief answer from @Salakar but might pursue a fix anyway. Wouldn't be looking into it for a few days at least though—while it reduces some functionality, it's not breaking for me. Let me know if you find anything

@kevinEsherick I actually managed to make it work. It was an issue with other library I used react-native-splash-screen If you use this library paste here your AndroidManifest.xml I will see if you have setup similar to mine.

I'm using both react-native-splash-screen and firebase here is a fragment of my AndroidManifest.xml:

<manifest>
<!--Permissions-->
    <service android:name="io.invertase.firebase.messaging.RNFirebaseMessagingService">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
        </intent-filter>
    </service>
    <service android:name="io.invertase.firebase.messaging.RNFirebaseInstanceIdService">
        <intent-filter>
            <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
        </intent-filter>
    </service>
    <service android:name="io.invertase.firebase.messaging.RNFirebaseBackgroundMessagingService" />

<!--Facebook Activity -->

<activity
            android:name=".LaunchActivity"
            android:theme="@style/LaunchScreen"
            android:label="@string/app_name"
            android:launchMode="singleTask"
            >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:screenOrientation="portrait"
            android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
            android:windowSoftInputMode="stateAlwaysHidden|adjustPan"
            android:exported="true"
            android:launchMode="singleTask"
        >
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />
                <data android:scheme="@string/app_name" android:host="@string/app_name" />
            </intent-filter>
        </activity>

        <meta-data
            android:name="com.google.firebase.messaging.default_notification_icon"
            android:resource="@drawable/ic_stat_notification" />
        <meta-data
            android:name="com.google.firebase.messaging.default_notification_color"
            android:resource="@color/colorAccent" />

</manifest>

try this :

<manifest>
<!--Permissions-->
    <service android:name="io.invertase.firebase.messaging.RNFirebaseMessagingService">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
        </intent-filter>
    </service>
    <service android:name="io.invertase.firebase.messaging.RNFirebaseInstanceIdService">
        <intent-filter>
            <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
        </intent-filter>
    </service>
    <service android:name="io.invertase.firebase.messaging.RNFirebaseBackgroundMessagingService" />

<!--Facebook Activity -->

    <application
      android:name=".MainApplication"
      android:label="@string/app_name"
      android:icon="@mipmap/ic_launcher"
      android:allowBackup="false"
      android:theme="@style/AppTheme">
      <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
        android:windowSoftInputMode="adjustResize">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
      </activity>
      <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
    </application>


        <meta-data
            android:name="com.google.firebase.messaging.default_notification_icon"
            android:resource="@drawable/ic_stat_notification" />
        <meta-data
            android:name="com.google.firebase.messaging.default_notification_color"
            android:resource="@color/colorAccent" />

</manifest>

I basically removed the Splashscreen and revert it to the original activity

@artiumGlobalbit thanks but unfortunately I'm on iOS and am not using this package

For those hoping to handle notifications in the background even if the user does not interact with them, I don't think this functionality is possible in Apple's system. As far as I can tell, it's not possible given the way notifications are handled on the iOS side. They say in the following link that they do not provide a handler for when a notification is simply delivered in the background and every google/SO search indicates the same thing:
https://developer.apple.com/library/archive/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/SchedulingandHandlingLocalNotifications.html

If my suggestion is correct, then it isn't a bug with this library and is a different issue than the one that many people here have (i.e. stuff not working when tapped or in the foreground) which seems to be an actual bug in this package. It's just a limitation of what Apple enables developers to do. If this is the case, then the documentation should make this much more clear!
If anyone believes this is incorrect and that you can provide a callback to notifications in the background without user interaction, please let me know!

I'm using both react-native-splash-screen and firebase. I followed this https://github.com/invertase/react-native-firebase/issues/1272#issuecomment-421424104 and it worked!

I solved this with the following files

NotificationListeners.js

import firebase from 'react-native-firebase';
import { ts } from './FirebaseHelpers';
// https://rnfirebase.io/docs/v5.x.x/notifications/introduction

export const notificationDisplayedListener = () =>
  // app in foreground
  firebase.notifications().onNotificationDisplayed(notification => {
    console.log('onNotificationDisplayed');
    console.log(notification);
  });

export const notificationListener = () =>
  // app in foreground
  firebase.notifications().onNotification(notification => {
    console.log('notificationListener');
    console.log(notification);

    const localNotification = new firebase.notifications.Notification({
      sound: 'default',
      show_in_foreground: true,
      show_in_background: true,
    })
      .setNotificationId(notification.notificationId)
      .setTitle(notification.title)
      .setSubtitle(notification.subtitle)
      .setBody(notification.body)
      .setData(notification.data)
      .android.setChannelId('General')
      .android.setSmallIcon('@mipmap/ic_notification')
      .android.setColor('#F2C94C')
      .android.setPriority(firebase.notifications.Android.Priority.High);

    firebase.notifications().displayNotification(localNotification);
    console.log('displayed');
    firebase.notifications().removeDeliveredNotification(localNotification.notificationId);
  });

export const notificationOpenedListener = () =>
  // app in background
  firebase.notifications().onNotificationOpened(notificationOpen => {
    console.log('notificationOpenedListener');
    console.log(notificationOpen);
    const { action, notification } = notificationOpen;
    firebase.notifications().removeDeliveredNotification(notification.notificationId);
    console.log('OPEN:', notification);
  });

export const notificationTokenListener = userId =>
  // listens for changes to the user's notification token and updates database upon change
  firebase.messaging().onTokenRefresh(notificationToken => {
    console.log('notificationTokenListener');
    console.log(notificationToken);

    return firebase
      .firestore()
      .collection('users')
      .doc(userId)
      .update({ pushToken: notificationToken, updatedAt: ts })
      .then(ref => {
        console.log('savePushToken success');
      })
      .catch(e => {
        console.error(e);
      });
  });

SplashActivity.java

package com.daviswhitehead.shayr.android;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

public class SplashActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Intent intent = new Intent(this, MainActivity.class);

        // Pass along FCM messages/notifications etc.
        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            intent.putExtras(extras);
        }

        startActivity(intent);
        finish();
    }
}

AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.daviswhitehead.shayr.android"
    xmlns:tools="http://schemas.android.com/tools" >

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <uses-permission android:name="android.permission.VIBRATE" />

    <application
        android:name=".MainApplication"
        android:label="@string/APP_NAME"
        android:icon="@mipmap/ic_launcher"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:allowBackup="false"
        android:theme="@style/AppTheme"
        tools:replace="android:label">

        <activity
            android:name=".SplashActivity"
            android:theme="@style/SplashTheme"
            android:label="@string/APP_NAME"
            android:launchMode="singleTask" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity
            android:name=".MainActivity"
            android:label="@string/APP_NAME"
            android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
            android:windowSoftInputMode="adjustResize"
            android:exported="true"
            android:launchMode="singleTask" >
        </activity>

        <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id"/>

        <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />

        <!-- NOTIFICATION DEFAULTS -->
        <meta-data
            android:name="com.google.firebase.messaging.default_notification_channel_id"
            android:value="@string/default_notification_channel_id"/>

        <!-- Set custom default icon. This is used when no icon is set for incoming notification messages.
            See README(https://goo.gl/l4GJaQ) for more. -->
        <meta-data
            android:name="com.google.firebase.messaging.default_notification_icon"
            android:resource="@mipmap/ic_notification" />
            <!-- android:resource="@drawable/ic_notification" /> -->
        <!-- Set color used with incoming notification messages. This is used when no color is set for the incoming
            notification message. See README(https://goo.gl/6BKBk7) for more. -->
        <meta-data
            android:name="com.google.firebase.messaging.default_notification_color"
            android:resource="@color/yellow" />

        <!-- SHARE ACTIVITY -->
        <activity
            android:noHistory="true"
            android:name=".share.ShareActivity"
            android:configChanges="orientation"
            android:label="@string/TITLE_ACTIVITY_SHARE"
            android:screenOrientation="portrait"
            android:theme="@style/Theme.Share.Transparent" >
            <intent-filter>
                <action android:name="android.intent.action.SEND" />
                <category android:name="android.intent.category.DEFAULT" />
                //  for sharing links include
                <data android:mimeType="text/plain" />
                //  for sharing photos include
                <data android:mimeType="image/*" />
            </intent-filter>
        </activity>

        <!-- FABRIC -->
        <meta-data
            android:name="io.fabric.ApiKey"
            android:value="c12e5c4bb8cd8ca855a8ada44fa3fde413006659" />

        <!-- REACT-NATIVE-FIREBASE NOTIFICATIONS -->
        <service android:name="io.invertase.firebase.messaging.RNFirebaseMessagingService">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>

        <service android:name="io.invertase.firebase.messaging.RNFirebaseInstanceIdService">
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
            </intent-filter>
        </service>

        <!-- SCHEDULED NOTIFICATIONS -->
        <receiver android:name="io.invertase.firebase.notifications.RNFirebaseNotificationReceiver"/>
        <receiver android:enabled="true" android:exported="true"  android:name="io.invertase.firebase.notifications.RNFirebaseNotificationsRebootReceiver">
            <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED"/>
            <action android:name="android.intent.action.QUICKBOOT_POWERON"/>
            <action android:name="com.htc.intent.action.QUICKBOOT_POWERON"/>
            <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </receiver>
    </application>
</manifest>

I have experienced this problem also on Android, getInitialNotification's payload is not consistent, sometimes it returns the notificationOpenpayload, and most of the time it returns null.

I have no way to identify if the app is opened via a notification tap. But I temporarily solved my problem by using this hack, using AppState and AsyncStorage.

1. On your headlessTask handler, for example mine named `firebaseBackgroundTask.js`.
// @flow
import firebase from "react-native-firebase";
import { AppState, AsyncStorage } from "react-native";
import type { RemoteMessage, NotificationOpen } from "react-native-firebase";

export default async (message: RemoteMessage) => { 
    const currentAppState = AppState.currentState;

    // listen for app state change, then save the message data using AsyncStorage
    AppState.addEventListener("change", nextAppstate => {
        if(currentAppState === "active" && nextAppState === "uninitialized") {
            // I named the item key `FCM.BG_MESSAGE` but you can name it what you want.
            // Then, serialise the data to JSON, because AsyncStorage only allow strings as value
            AsyncStorage.setItem("FCM.BG_MESSAGE", JSON.stringify(message.data));
        }
    });

    // display your notification here
};
1. On your root component's(mine is on `App.js`) `componentDidMount` lifecycle hook, add this
export default class extends React.PureComponent<*> {
    componentDidMount() {
         AsyncStorage.getItem("FCM.BG_MESSAGE")
             .then(json => {
                 const data = jsonData ? JSON.parse(jsonData) : false;
                 console.log(data);
                 // then do navigation, or whatever you want to the data.
             }).catch(e => console.log(e));
    }
}

Hope it helps someone! Cheers! smile

you've saved my week!

@karlmarxlopez could you provide a more detailed look on your setup? For example, how do you connect your headlessTask with everything else? Thanks!

I'll try to create a sample project tonight and put it on github.

On Fri, Feb 22, 2019, 5:13 PM Martin Doychev notifications@github.com
wrote:

@karlmarxlopez https://github.com/karlmarxlopez could you provide a
more detailed look on your setup? For example, how do you connect your
headlessTask with everything else? Thanks!


You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
https://github.com/invertase/react-native-firebase/issues/1149#issuecomment-466328204,
or mute the thread
https://github.com/notifications/unsubscribe-auth/AG3GaNh9XVLbVLcAkguXt0qDAW637fDXks5vP7S6gaJpZM4UP-3J
.

@karlmarxlopez just a reminder, in case you forgot to post a link or something :)

Hi! I'm sorry, I totally forgot it. I will do it later. What RN version are
you using?

On Mon, Feb 25, 2019, 7:14 AM Martin Doychev notifications@github.com
wrote:

@karlmarxlopez https://github.com/karlmarxlopez just a reminder, in
case you forgot to post a link or something :)


You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
https://github.com/invertase/react-native-firebase/issues/1149#issuecomment-466828439,
or mute the thread
https://github.com/notifications/unsubscribe-auth/AG3GaFgfG3F3Z8seVt2_KJkT94uUkIHbks5vQxzdgaJpZM4UP-3J
.

@karlmarxlopez
"react-native": "0.57.8",
Thanks!

@Doychev Here it is

To anyone who's still struggling, I've managed to make it work. The notificationOpen object is different for android and ios. This also applies with getInitialNotification()

Here's my code

firebase.notifications().onNotificationOpened(notificationOpen => {
  const data = Platform.OS === 'android' ? notificationOpen.notification.data.customDataKeyName : notificationOpen.customDataKeyName;
  this.navigate(data);
});

background_test

@jettandres thanks for providing a workaround that clearly demonstrates the issue, I've added this to the project tracker to be resolved in v6

@SkyTreasure I was having issues with the iOS notification listeners as well on iOS 11.

@Salakar Fixed the issue by commenting out line 77 & 95 from didReceiveLocalNotification in the RNFirebaseNotifications.m:
77: //if ([self isIOS89]) {
95: //}

believe it or not this actually solved my problem, thanks!

Just use as below

#import <UserNotifications/UserNotifications.h>

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  NSURL *jsCodeLocation;


                #ifdef DEBUG
                    jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];
                #else
                    jsCodeLocation = [CodePush bundleURL];
                #endif

  [FIRApp configure];
  [RNFirebaseNotifications configure];

  if ([UNUserNotificationCenter class] != nil) {
    // iOS 10 or later
    // For iOS 10 display notification (sent via APNS)
    [UNUserNotificationCenter currentNotificationCenter].delegate = self;
    UNAuthorizationOptions authOptions = UNAuthorizationOptionAlert |
    UNAuthorizationOptionSound | UNAuthorizationOptionBadge;
    [[UNUserNotificationCenter currentNotificationCenter]
     requestAuthorizationWithOptions:authOptions
     completionHandler:^(BOOL granted, NSError * _Nullable error) {
       // ...
     }];
  } else {
    // iOS 10 notifications aren't available; fall back to iOS 8-9 notifications.
    UIUserNotificationType allNotificationTypes =
    (UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge);
    UIUserNotificationSettings *settings =
    [UIUserNotificationSettings settingsForTypes:allNotificationTypes categories:nil];
    [application registerUserNotificationSettings:settings];
  }
  [application registerForRemoteNotifications];

  RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
                                                      moduleName:@"meinhiMobile"
                                               initialProperties:nil
                                                   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];

  [Fabric with:@[[Crashlytics class]]];

  [[UIApplication sharedApplication] registerForRemoteNotifications];
  [[UNUserNotificationCenter currentNotificationCenter] setDelegate:self];

  [RNSplashScreen show];
  return YES;
}

Be careful if you're sending "a lot" of data with the notification. I removed images (in base64) from the notifications and the issue of being able to open the app by clicking the notification was solved.

any update on this issue, is there a workaround ? Nothing here works for me!

@mi-mazouz this issue has been open more than a year. What versions are you on? What exactly are your steps to reproduce and on which platforms? ideally with a small repro based off the starter? There are 27 people chiming in here, and I'd be shocked if they were all having the same problem.

Possibly best to open a new issue...

@mikehardy ok I'll do it but so why don't you close this issue?

because there is one part of it that seems useful to @Salakar somewhat recently and he's part of the team doing the actual coding. I'm just trying to help users

@mikehardy ok thanks, I think #1900 is the correct issue for my problem.

If anyone has combined react-native-splash-screen with react-native-firebase, and they implemented the splash screen with a separate launch activity, this will happen. There are workarounds but you should use splash-screen with a single Activity and it just works. Code here: https://github.com/crazycodeboy/react-native-splash-screen/issues/289#issuecomment-502406454

I took the most recent useful information from this issue and extracted to a standalone issue. Now this issue is just intermittent discussion but I don't believe we can reproduce anything so I'm closing it

I ended up figuring out what was going wrong on my side. It was fairly specific to my application but maybe it will help others:

I ended up having two separate issues:

  1. To begin, I had the following in set in didFinishLaunchingWithOptions
    [UNUserNotificationCenter currentNotificationCenter].delegate = self;

which overrides the ReactNativeFirebase specific behavior of listening
to notification open and pushing this information accross the bridge to
be handled by JS. You can see this behavior here:

https://github.com/invertase/react-native-firebase/blob/master/ios/RNFirebase/notifications/RNFirebaseNotifications.m#L203-L215

In particular, I believe this arose from following the FirebaseIOS setup
docs found here: https://github.com/firebase/quickstart-ios/blob/master/messaging/MessagingExample/AppDelegate.m

Which is an example of how to set up Firebase on Ios and handle these
callbacks your self manually. This type of setup is not needed if you
are using ReactNativeFirebase as this will be handled by the bridged
module so that it can intercept these messages and pass them to JS.

  1. We are using the IntercomIOS library ad Intercom react-native to send push notifications from our application to users when we respond to them from Intercom.

If you follow the Intercom onboarding, you will add the following to your AppDeligate.m

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    [Intercom setDeviceToken:deviceToken];
}

Its a bit hard to find, but this call will actually swizzle the public methods in UIApplicationDelegate.

In particular, this overrides the handling of FirebaseReactNative of notification open actions.

TLDR; Make sure that you are not overridding public methods in UIApplicationDelegate

Thanks alot man , you saved me.
I had the same problem as well,
what i did in appdelegate.m in didfinishlaunchingwithoptions method is

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  [FIRApp configure];
  [RNFirebaseNotifications configure];
  RCTBridge *bridge = [[RCTBridge alloc] initWithDelegate:self launchOptions:launchOptions];
  RCTRootView *rootView = [[RCTRootView alloc] initWithBridge:bridge
                                                   moduleName:@"lendish"
                                            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];

  // I commented those two lines here ------->
  // define UNUserNotificationCenter 
//  UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
//  center.delegate = self;   <-----------

  return YES;
}

@mikehardy I work with V6 in my whole app and want to do firebase.notifications().onNotification but I don't see any module on V6 Docs relate to Notifications! how can I handle these issues?

@anastely first pinned issue in this repo - there is no notifications in v6

I have same issue on ios

firebase.notifications().getInitialNotification() is working fine,
but onNotification() & onNotificationOpened() are not fired
except i do reload the app before sending notification, it's work.

So, now i'm using react-native-restart to restart after 500 ms when user open the app

I do not know why, anybody can explain?

Everybody - it's clear notifications is not present in v6. So notifications work is kind of a dead-end here. Troubleshooting included. Rather than struggle to make it work here, use data-only messages from firebase, and integrate a full-featured local notifications package to interact with the device UI in response to the data messages. There has been reported user success with react-native-push-notifications.

Currently running "react-native-firebase": "^5.5.5" and it seems my notifications/listener functions are not working as expected when I run my app in release mode on iOS:

  • firebase.notifications().onNotificationOpened
  • firebase.notifications().onNotification
  • firebase.messaging().onMessage

They work perfectly as expected when running on device on Debug configuration. I can open up an issue if needs be.

Managed to resolve this, issue was that CodePush was overwriting my file changes when I built in Release mode. By commenting out the wrapper export default codePush(codePushOptions)(...) before building in Release mode on a test device I managed to get my listeners to work as expected 👍

Was this page helpful?
0 / 5 - 0 ratings