invertase / react-native-firebase

🔥 A well-tested feature-rich modular Firebase implementation for React Native. Supports both iOS & Android platforms for all Firebase services.
https://rnfirebase.io
Other
11.71k stars 2.22k forks source link

getInitialNotification not working #3964

Closed ghasemikasra39 closed 3 years ago

ghasemikasra39 commented 4 years ago

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`: ```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: ```json # N/A ```

iOS

Click To Expand

#### `ios/Podfile`: - [ ] I'm not using Pods - [x] I'm using Pods and my Podfile looks like: ```ruby 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`: ```objc /** * 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 #import "AppDelegate.h" #import #import #import "RNSplashScreen.h" // here #import #import #import #import #import #import @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> *)extraModulesForBridge:(RCTBridge *)bridge { NSArray> *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`: ```groovy // N/A ``` #### `android/app/build.gradle`: ```groovy // N/A ``` #### `android/settings.gradle`: ```groovy // N/A ``` #### `MainApplication.java`: ```java // N/A ``` #### `AndroidManifest.xml`: ```xml ```


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`


keshavsharma0712 commented 1 year ago

Hi @Haseeba393 notifee.getInitialNotification().then(async (notification) => { // handle notification console.log(notification, 'onReady'); });

    I am receiving null after resolving this promise. I'm still facing the issue tried everything.
Haseeba393 commented 1 year ago

@keshavsharma0712 brother according to documentation, if the app is not launched by notification then you will receive null in this promise or if you relaunch app then it will be removed as well in this case again you will receive null.

surya-dharmakrishnan commented 1 year ago

If you are using notifee along with RN firebase, you can use their listener while app mounting,

    notifee.getInitialNotification().then((remoteNotification) => {
//Do your notification opening action here
      openNotification(remoteNotification.notification, this.props.setCurrentMessage, this.props.setPushMessageStatus)
//Above line is mine
    });
khushbujilka22 commented 1 year ago

notifee.getInitialNotification() messaging().getInitialNotification()

^^ For me, both of this methods are not working.

"@react-native-firebase/messaging": "18.3.0", "react-native": "0.72.3", "@notifee/react-native": "^7.8.0",

thisisashukla commented 1 year ago

facing this issue. can anybody help?

Haseeba393 commented 1 year ago

@thisisashukla @khushbujilka22 can you provide reproduce able error repo? Also did you try to use await and async?

thisisashukla commented 1 year ago

@Haseeba393 here is my useEffect function

useEffect(() => {
    messaging().setBackgroundMessageHandler(async (remoteMessage) => {
      console.log("Message handled in the background!", remoteMessage);
    });

    messaging()
      .getInitialNotification()
      .then(async (remoteMessage) => {
        console.log(
          "[FCMService] getInitialNotification Notification caused on to open ",
          remoteMessage
        );
        if (remoteMessage) {
          console.log(remoteMessage);
          const notification = remoteMessage.notification;
          const notificationData = remoteMessage.data;
          onOpenNotification(notification, notificationData, rootstore);
        }
      })
      .catch((error) => console.log("getInitnotification error ", error));

    messaging().onNotificationOpenedApp((remoteMessage) => {
      console.log(
        "[FCMService] onNotificationOpenedApp Notification caused on to open"
      );
      if (remoteMessage) {
        const notification = remoteMessage.notification;
        const notificationData = remoteMessage.data;
        // console.log("sending rootstore", this.rootstore);
        onOpenNotification(notification, notificationData, rootstore);
      }
    });
  }, []);

i am getting remoteMessage as null in the getInitialNotification method when a notification is tapped when the app is in killed state. onNotificationOpenedApp is working fine for app in background

Haseeba393 commented 1 year ago

@thisisashukla in which file did you write this use effect? Also are you using any bootsplash package for splash screen?

thisisashukla commented 1 year ago

i am using expo-splash-creen. i have written this useEffect in App.js

Haseeba393 commented 1 year ago

Your application is based on React Native Expo or React Native CLI?

thisisashukla commented 1 year ago

react native expo

Haseeba393 commented 1 year ago

testing on real device or emulator?

khanakia commented 11 months ago

@thisisashukla were you able to make it work ?

thisisashukla commented 11 months ago

@thisisashukla were you able to make it work ?

Yes

khanakia commented 11 months ago

Can you tell me what solution you applied please I am facing the same issue getInitialNotification is null I have tried all the available suggestions.

tao-qian commented 10 months ago

We are running into the same issue as well. messaging().getInitialNotification() would be triggered but the payload would be null.

This is on iOS physical device, and onNotificationOpenedApp works just fine when the app is not in the killed state.

Edit This is reproducible consistently for us on dev build, but it is actually not happening in the release build. So consider trying things on the release build before looking for solutions in all the other threads about the same issue.. If release build also doesn't work, here are some of the threads you can look through for solutions:

khanakia commented 10 months ago

Those functions moved to https://notifee.app/ library so you will have to use notifee

Read this: https://rnfirebase.io/messaging/usage#background--quit-state-messages

tao-qian commented 10 months ago

Those functions moved to https://notifee.app/ library so you will have to use notifee

Read this: https://rnfirebase.io/messaging/usage#background--quit-state-messages

Ah that makes sense.

I did more testing. It seems like for prod build, what worked was not messaging().getInitialNotification(), but notifee.onForegroundEvent(). (we had both listeners in the code).

In the end we are going with:

autimio commented 4 months ago

Using react-native-notifications worked for me.

import { Notifications } from 'react-native-notifications';
Notifications.getInitialNotification().then(async remoteMessage => {}).catch(err => { console.error(err, 'err') })
VitorGabrieldeOliveira commented 3 months ago

At first I switched from expo-splash-screen to react-native-bootsplash, but getInitialNotification was still returning null.

Then, I read this part of @tao-qian comment.

Edit This is reproducible consistently for us on dev build, but it is actually not happening in the release build. So consider trying things on the release build before looking for solutions in all the other threads about the same issue..

I tried it and it worked! For some reason, getInitialNotification always returns null when running expo in dev mode.

Note: I encountered this issue on Android.

sahil2401 commented 1 week ago

This works for me

 const handleNotificationOpenedApp = () => {
        messaging().onNotificationOpenedApp((remoteMessage) => {
          console.log("Notification opened from background:", remoteMessage);
          return remoteMessage
        });
      };