React-native-firebase: getInitialNotification not working

Created on 17 Jul 2020  路  24Comments  路  Source: invertase/react-native-firebase


Issue



The messaging().onNotificationOpenedApp works perfectly fine, when the app is open but is in the background.
The messaging().getInitialNotification() however, is not working as expected when the app is closed. Tapping on the notification will just open the app.


Project Files






Javascript

Click To Expand

#### `package.json`:

{
  "scripts": {
    "start": "react-native start",
    "android": "react-native run-android",
    "ios": "react-native run-ios",
    "web": "expo start --web",
    "lint": "eslint 'src/**/*'",
    "fix": "eslint --fix 'src/**/*'",
    "test": "jest",
    "test-ci": "jest --ci --detectOpenHandles --forceExit",
    "storybook": "expo start --config './storybook/app.storybook.json'",
    "storybook-control": "start-storybook -p 7007"
  },
  "dependencies": {
    "@react-native-community/async-storage": "^1.10.0",
    "@react-native-community/cli": "^4.8.0",
    "@react-native-community/masked-view": "^0.1.10",
    "@react-native-community/netinfo": "5.0.0",
    "@react-native-firebase/analytics": "^7.1.0",
    "@react-native-firebase/app": "^7.1.0",
    "@react-native-firebase/auth": "^8.0.0",
    "@react-native-firebase/crashlytics": "^7.1.0",
    "@react-native-firebase/firestore": "^7.1.0",
    "@react-native-firebase/messaging": "^7.1.1",
    "@react-navigation/bottom-tabs": "^5.3.1",
    "@react-navigation/native": "^5.2.1",
    "@react-navigation/stack": "^5.2.16",
    "@reduxjs/toolkit": "^1.3.5",
    "@types/react-native-snap-carousel": "^3.7.4",
    "add": "^2.0.6",
    "axios": "^0.19.0",
    "expo": "^36.0.0",
    "expo-apple-authentication": "~2.0.0",
    "expo-asset": "^8.1.5",
    "expo-av": "~8.0.0",
    "expo-blur": "~8.0.0",
    "expo-camera": "^8.2.0",
    "expo-constants": "^9.0.0",
    "expo-device": "~2.0.0",
    "expo-facebook": "^8.1.0",
    "expo-file-system": "~8.0.0",
    "expo-image-manipulator": "^8.1.0",
    "expo-image-picker": "^8.1.0",
    "expo-intent-launcher": "~8.0.0",
    "expo-linear-gradient": "~8.0.0",
    "expo-location": "~8.0.0",
    "expo-secure-store": "~8.0.0",
    "expo-sensors": "~8.0.0",
    "husky": "^3.1.0",
    "install": "^0.13.0",
    "lottie-ios": "3.1.3",
    "lottie-react-native": "^3.3.2",
    "moment": "^2.24.0",
    "object-hash": "^2.0.1",
    "react": "16.11.0",
    "react-dom": "^16.13.1",
    "react-native": "0.62.2",
    "react-native-device-screen-switcher": "^0.1.0",
    "react-native-dotenv": "^0.2.0",
    "react-native-elements": "^1.2.7",
    "react-native-gesture-handler": "^1.6.1",
    "react-native-maps": "0.27.1",
    "react-native-mixpanel": "^1.2.0",
    "react-native-modalbox": "^2.0.0",
    "react-native-photoeditorsdk": "^2.4.1",
    "react-native-push-notification-popup": "^1.4.0",
    "react-native-reanimated": "^1.9.0",
    "react-native-safe-area-context": "0.6.0",
    "react-native-screens": "2.0.0-alpha.12",
    "react-native-snap-carousel": "^3.9.0",
    "react-native-splash-screen": "^3.2.0",
    "react-native-svg": "9.13.3",
    "react-native-swipe-list-view": "^2.5.0",
    "react-native-swiper": "git+https://github.com/i22-digitalagentur/react-native-swiper.git#08655fe84b36dc5f1a682326f210684409639870",
    "react-native-tab-view": "^2.14.4",
    "react-native-unimodules": "~0.7.0",
    "react-native-video": "^4.4.5",
    "react-native-videoeditorsdk": "^2.4.2",
    "react-native-web": "^0.11.7",
    "react-redux": "^7.1.3",
    "redux": "^4.0.4",
    "redux-actions": "^2.6.5",
    "redux-mock-store": "^1.5.3",
    "redux-observable": "^1.2.0",
    "redux-persist": "^6.0.0",
    "rxjs": "^6.5.5",
    "url": "^0.11.0",
    "validate": "^5.1.0",
    "yarn": "^1.22.4"
  },
  "devDependencies": {
    "@babel/cli": "^7.8.4",
    "@babel/core": "^7.9.0",
    "@babel/node": "^7.8.7",
    "@babel/preset-env": "^7.9.5",
    "@react-native-community/eslint-config": "0.0.5",
    "@sambego/storybook-state": "^1.3.6",
    "@storybook/addon-actions": "^5.3.18",
    "@storybook/addon-links": "^5.3.18",
    "@storybook/addons": "^5.3.18",
    "@storybook/react-native": "^5.3.18",
    "@storybook/react-native-server": "^5.3.18",
    "@testing-library/react-native": "^5.0.1",
    "@types/jest": "^24.0.23",
    "@types/react": "^16.9.34",
    "@types/react-native": "^0.57.65",
    "@types/react-native-swiper": "^1.5.10",
    "@types/react-native-video": "^5.0.1",
    "babel-jest": "~24.9.0",
    "babel-loader": "^8.1.0",
    "babel-preset-expo": "^7.1.0",
    "enzyme": "^3.11.0",
    "enzyme-adapter-react-16": "^1.15.2",
    "eslint": "^5.16.0",
    "eslint-config-prettier": "^6.11.0",
    "jest": "~24.9.0",
    "jest-expo": "^36.0.0",
    "metro-react-native-babel-preset": "~0.56.0",
    "react-test-renderer": "^16.13.1",
    "typescript": "^3.8.3"
  },
  "private": true
}

#### `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:

platform :ios, '10.0'

require_relative '../node_modules/react-native-unimodules/cocoapods'
require_relative '../node_modules/@react-native-community/cli-platform-ios/native_modules'

target 'YoupendoApp' do
  rnPrefix = "../node_modules/react-native"

  # React Native and its dependencies
  pod 'FBLazyVector', :path => "#{rnPrefix}/Libraries/FBLazyVector"
  pod 'FBReactNativeSpec', :path => "#{rnPrefix}/Libraries/FBReactNativeSpec"
  pod 'RCTRequired', :path => "#{rnPrefix}/Libraries/RCTRequired"
  pod 'RCTTypeSafety', :path => "#{rnPrefix}/Libraries/TypeSafety"
  pod 'React', :path => "#{rnPrefix}/"
  pod 'React-Core', :path => "#{rnPrefix}/"
  pod 'React-CoreModules', :path => "#{rnPrefix}/React/CoreModules"
  pod 'React-RCTActionSheet', :path => "#{rnPrefix}/Libraries/ActionSheetIOS"
  pod 'React-RCTAnimation', :path => "#{rnPrefix}/Libraries/NativeAnimation"
  pod 'React-RCTBlob', :path => "#{rnPrefix}/Libraries/Blob"
  pod 'React-RCTImage', :path => "#{rnPrefix}/Libraries/Image"
  pod 'React-RCTLinking', :path => "#{rnPrefix}/Libraries/LinkingIOS"
  pod 'React-RCTNetwork', :path => "#{rnPrefix}/Libraries/Network"
  pod 'React-RCTSettings', :path => "#{rnPrefix}/Libraries/Settings"
  pod 'React-RCTText', :path => "#{rnPrefix}/Libraries/Text"
  pod 'React-RCTVibration', :path => "#{rnPrefix}/Libraries/Vibration"
  pod 'React-Core/RCTWebSocket', :path => "#{rnPrefix}/"
  pod 'React-Core/DevSupport', :path => "#{rnPrefix}/"
  pod 'React-cxxreact', :path => "#{rnPrefix}/ReactCommon/cxxreact"
  pod 'React-jsi', :path => "#{rnPrefix}/ReactCommon/jsi"
  pod 'React-jsiexecutor', :path => "#{rnPrefix}/ReactCommon/jsiexecutor"
  pod 'React-jsinspector', :path => "#{rnPrefix}/ReactCommon/jsinspector"
  pod 'ReactCommon/callinvoker', :path => "#{rnPrefix}/ReactCommon"
  pod 'ReactCommon/turbomodule/core', :path => "#{rnPrefix}/ReactCommon"
  pod 'Yoga', :path => "#{rnPrefix}/ReactCommon/yoga"
  pod 'DoubleConversion', :podspec => "#{rnPrefix}/third-party-podspecs/DoubleConversion.podspec"
  pod 'glog', :podspec => "#{rnPrefix}/third-party-podspecs/glog.podspec"
  pod 'Folly', :podspec => "#{rnPrefix}/third-party-podspecs/Folly.podspec"
  pod 'react-native-video', :path => '../node_modules/react-native-video/react-native-video.podspec'


  # Other native modules

  # Automatically detect installed unimodules
  use_unimodules!

   # React Native Maps dependencies
   rn_maps_path = '../node_modules/react-native-maps'
   pod 'react-native-google-maps', :path => rn_maps_path
   pod 'GoogleMaps'
   pod 'Google-Maps-iOS-Utils'

  # react-native-cli autolinking
  use_native_modules!
  pod 'react-native-splash-screen', :path => '../node_modules/react-native-splash-screen'

end

#### `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 <AVFoundation/AVFoundation.h>
#import "AppDelegate.h"

#import <React/RCTBundleURLProvider.h>
#import <React/RCTRootView.h>
#import "RNSplashScreen.h"  // here
#import <Firebase.h>
#import <UMCore/UMModuleRegistry.h>
#import <UMReactNativeAdapter/UMNativeModulesProxy.h>
#import <UMReactNativeAdapter/UMModuleRegistryAdapter.h>
#import <Firebase.h>
#import <GoogleMaps/GoogleMaps.h>


@implementation AppDelegate

@synthesize window = _window;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    [GMSServices provideAPIKey:@"AIzaSyAhCqHED1f2HgxuzEb6dvYVb2M5n4Ohbkg"];

  if ([FIRApp defaultApp] == nil) {
    [FIRApp configure];
  }

  self.moduleRegistryAdapter = [[UMModuleRegistryAdapter alloc] initWithModuleRegistryProvider:[[UMModuleRegistryProvider alloc] init]];
  RCTBridge *bridge = [[RCTBridge alloc] initWithDelegate:self launchOptions:launchOptions];
  RCTRootView *rootView = [[RCTRootView alloc] initWithBridge:bridge moduleName:@"YoupendoApp" initialProperties:nil];
  rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f green:1.0f blue:1.0f alpha:1];
  if ([FIRApp defaultApp] == nil) {
    [FIRApp configure];
  }
  self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
  UIViewController *rootViewController = [UIViewController new];
  rootViewController.view = rootView;
  self.window.rootViewController = rootViewController;
  [self.window makeKeyAndVisible];

  [super application:application didFinishLaunchingWithOptions:launchOptions];

   [RNSplashScreen show];  // here

   [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];

  return YES;
}

- (NSArray<id<RCTBridgeModule>> *)extraModulesForBridge:(RCTBridge *)bridge
{
  NSArray<id<RCTBridgeModule>> *extraModules = [_moduleRegistryAdapter extraModulesForBridge:bridge];
  // You can inject any extra modules that you would like here, more information at:
  // https://facebook.github.io/react-native/docs/native-modules-ios.html#dependency-injection
  return extraModules;
}

- (NSURL *)sourceURLForBridge:(RCTBridge *)bridge {
#ifdef DEBUG
  return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];
#else
  return [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];
#endif
}

@end


Android

Click To Expand

#### Have you converted to AndroidX? - [ ] my application is an AndroidX application? - [ ] I am using `android/gradle.settings` `jetifier=true` for Android compatibility? - [ ] I am using the NPM package `jetifier` for react-native compatibility? #### `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

Click To Expand

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

System:
    OS: macOS 10.15.3
    CPU: (4) x64 Intel(R) Core(TM) i5-5257U CPU @ 2.70GHz
    Memory: 57.87 MB / 8.00 GB
    Shell: 5.7.1 - /bin/zsh
  Binaries:
    Node: 12.13.1 - ~/.nvm/versions/node/v12.13.1/bin/node
    Yarn: 1.22.4 - ~/Documents/youpendo-app-bareworkflow/node_modules/.bin/yarn
    npm: 6.12.1 - ~/.nvm/versions/node/v12.13.1/bin/npm
    Watchman: 4.9.0 - /usr/local/bin/watchman
  Managers:
    CocoaPods: 1.9.3 - /usr/local/bin/pod
  SDKs:
    iOS SDK:
      Platforms: iOS 13.2, DriverKit 19.0, macOS 10.15, tvOS 13.2, watchOS 6.1
    Android SDK:
      API Levels: 28, 29
      Build Tools: 28.0.3, 29.0.2
      System Images: android-28 | Google APIs Intel x86 Atom, android-29 | Google APIs Intel x86 Atom
      Android NDK: Not Found
  IDEs:
    Android Studio: 3.6 AI-192.7142.36.36.6392135
    Xcode: 11.3.1/11C504 - /usr/bin/xcodebuild
  Languages:
    Java: 1.8.0_232 - /usr/bin/javac
    Python: 2.7.16 - /usr/bin/python
  npmPackages:
    @react-native-community/cli: ^4.8.0 => 4.10.0
    react: 16.11.0 => 16.11.0
    react-native: 0.62.2 => 0.62.2
  npmGlobalPackages:
    *react-native*: Not Found
- **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 - **`react-native-firebase` version you're using that has this issue:** - `7.1.0` - **`Firebase` module(s) you're using that has the issue:** - `getInitialNotification` - **Are you using `TypeScript`?** - `3.9.5`




Notifications iOS Stale

Most helpful comment

messaging().getInitialNotification().then(this.handleSelected);


  handleSelected = async remoteMessage => {
    const notification = JSON.parse(remoteMessage.data.message);
    switch (notification.type) {
      case NOTIFICATION_TYPE_ONE:
        navigation.navigate('screen1', {
          data: notification.data,
        });
        break;
      case NOTIFICATION_TYPE_TWO:
        navigation.navigate('screen2', {
          data: notification.data,
        });
        break;
    }
  };

I am calling messaging().getInitialNotification() in my home screen. I can confirm that this method is called, since messaging().onNotificationOpenedApp(this.handleSelected) is called above it and works perfectly.

All 24 comments

Stop using "react-native-splash-screen": "^3.2.0",

Switch to react-native-bootsplash

Search issues and pull requests for "react-native-splash-screen" you'll see

Dear @mikehardy
Thank you for your response. We will consider moving to react-native-bootsplash, as react-native-splash-screen is not being maintained and has made us crazy.

On the plus side, bootsplash has a sweet command line interface to generate the .storyboard file you need to migrate to anyway, with screenshots even. It was a pleasant migration, which is not a thing I say often. Cheers

Dear @mikehardy
After removing the react-native-splash-screen (and not added the react-native-bootsplash yet) I am still facing the same issue I described above.

Is there an specific place where I should call messaging().getInitialNotification() ? I mean, should it be in the index.js or App.tsx or ...?

@ghasemikasra39 I called it in App.tsx useEffect(Did mount equivalent).
Can you share how the messaging().getInitialNotification() was invoked?

messaging().getInitialNotification().then(this.handleSelected);


  handleSelected = async remoteMessage => {
    const notification = JSON.parse(remoteMessage.data.message);
    switch (notification.type) {
      case NOTIFICATION_TYPE_ONE:
        navigation.navigate('screen1', {
          data: notification.data,
        });
        break;
      case NOTIFICATION_TYPE_TWO:
        navigation.navigate('screen2', {
          data: notification.data,
        });
        break;
    }
  };

I am calling messaging().getInitialNotification() in my home screen. I can confirm that this method is called, since messaging().onNotificationOpenedApp(this.handleSelected) is called above it and works perfectly.

@ghasemikasra39
oh okay.. I had an issue with messaging().getInitialNotification() syntax. Thought that might be the case here too. But that is not the issue here I believe.
As the documentation says I would suggest you to invoke this method as early as possible. Atleast when the routes are defined.

Is there a way to test this on simulator somehow ? It's extremely difficult to make small changes, then creating a build and install it on real device. I cannot debug or log something to find out where the problem is

If you are on android it should work on simulator, debug mode should work fine. But in iOS there is no other way to test than on a real device.

I cannot test it on a simulator, because I have to close the app to test messaging().getInitialNotification(). Then I receive no notification.

I made it work by calling it at a higher level in the dom tree, right after the NavigationContainer is initialized. However, it is called with a long delay, I saw the home screen for 5 seconds and then the transition occurs. Is it the normal behaviour?

Hmm.. I haven't tested that scenario myself. Maybe it is due to the debug mode build?

I created standalone apk and running on real device in release mode and facing this delay

I created this question. In this question, you can find the latest update on my issue. I am still struggling with this issue.

Hello 馃憢, to help manage issues we automatically close stale issues.
This issue has been automatically marked as stale because it has not had activity for quite some time. Has this issue been fixed, or does it still require the community's attention?

This issue will be closed in 15 days if no further activity occurs.
Thank you for your contributions.

i got getInitialNotification working on my previous setup. now with the update of "react-native-firebase": "5.6.0", I have faceing the same issue.push notification are working fine but the getinitialNotification and onNotification will have nothing.

@maduraherath8 you are talking about vastly different versions. Upgrade your app from v5 https://rnfirebase.io/migrating-to-v6

@ghasemikasra39 Did you resolve your problem?

I tried the below changes and it worked in android, haven't checked in IOS yet

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

        Intent intent = new Intent(this, MainActivity.class);
        intent.putExtras(getIntent().getExtras()); <----------------------------add this line
        startActivity(intent);
        finish();
    }
}

change in AndroidManifest.xml

<activity
            android:name=".SplashActivity"
            android:label="@string/app_name"
            android:theme="@style/SplashTheme"
            android:launchMode="singleTop" <---------------------change this line
           >
            <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|uiMode"
        android:launchMode="singleTop"<---------------------change this line
        android:windowSoftInputMode="adjustResize"
        android:exported="true"
          >

strongly recommended to use react-native-boot-splash, it handles the intent extras for you so that's not needed
I'm saying that as a guess that it was necessary, implying (I think) that you are using the old splash screen library https://github.com/crazycodeboy/react-native-splash-screen/issues/289#issuecomment-502406454

Push notification does not give call back if there are multiple notifications in the notification console and when one notification is already clicked then clicking on another notification from the notification tray after closing the app does not call any notification life cycle method.

Let's say there are 5-6 notifications in the console, we click on one of the notification which opens up the app and works as expected and calls the related methods. After that when we close the app and then click on another notification from the notification console then it does not call any notification method.

I am using "react-native": "0.61.4", and "@react-native-firebase/messaging": "^7.4.2",

Hello 馃憢, to help manage issues we automatically close stale issues.
This issue has been automatically marked as stale because it has not had activity for quite some time. Has this issue been fixed, or does it still require the community's attention?

This issue will be closed in 15 days if no further activity occurs.
Thank you for your contributions.

Closing this issue after a prolonged period of inactivity. If this is still present in the latest release, please feel free to create a new issue with up-to-date information.

Was this page helpful?
0 / 5 - 0 ratings