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`


mikehardy commented 4 years ago

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

ghasemikasra39 commented 4 years ago

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.

mikehardy commented 4 years ago

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

ghasemikasra39 commented 4 years ago

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.

ghasemikasra39 commented 4 years ago

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

Suresh-R-S commented 4 years ago

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

ghasemikasra39 commented 4 years ago
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.

Suresh-R-S commented 4 years ago

@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.

ghasemikasra39 commented 4 years ago

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

Suresh-R-S commented 4 years ago

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.

ghasemikasra39 commented 4 years ago

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

ghasemikasra39 commented 4 years ago

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?

Suresh-R-S commented 4 years ago

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

ghasemikasra39 commented 4 years ago

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

ghasemikasra39 commented 4 years ago

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

stale[bot] commented 4 years ago

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.

maduraherath8 commented 4 years ago

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.

mikehardy commented 4 years ago

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

thang-nm commented 4 years ago

@ghasemikasra39 Did you resolve your problem?

metwal14 commented 4 years ago

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"
          >
mikehardy commented 4 years ago

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

RishavKumar-3796 commented 4 years ago

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",

stale[bot] commented 3 years ago

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.

stale[bot] commented 3 years ago

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.

ACHAGO commented 3 years ago

@mikehardy you are spamming every thread to use react-native-boot-splash, but the issue is in rn firebase, im not using RNSplashscreen and i have this issue

Haseeba393 commented 3 years ago

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

I"m not using any library for splash screen. I have made custom splash screen Splash.js. My issue is the same, clicking on notification is just opening the application, getInitialNotification() never called. I changed it place as well in different files but all in vain. Can you please help me out?

mikehardy commented 3 years ago

Spamming - posting comments about the most popular case of initial notification problems resulting in lots of 'that fixed it', replies. How have you helped others lately? Don't be rude.

Implemented your own splash, are you passing intent extras correctly?

RNFB requires intent extras intact for this to work. If you have something fancy with your activities or intent handling, pass the intent info correctly

If you want background actually read the comment I posted on the old splash screen repo, it has detail

Haseeba393 commented 3 years ago

I have read your old replies on many other people's issues. For the Splash screen, I didn't use any library for it jsut make a splash through Splash.js and this is the code of the JSX `return( <ImageBackground source={IMAGES._splashBg} style={Styles._mainContainer}

<AppBar type='light' backgroundColor={COLORS.primaryColor2} /> <Spinner color={COLORS.whiteColor} style={Styles._spinner} /> );`

I didn't understand about intent info. Can you please help me out?

Haseeba393 commented 3 years ago

I'm not doing any spamming. Its a real issue on my side that I'm facing for last 2 days. I'm not that much expert in it that's why asking here. Second, I DIDN'T use any library for the splash screen

mikehardy commented 3 years ago

You actually should use a splash screen library if you want a splash screen, as they need native integration to show while the js bundle boots, which is a big part of app startup time.

It was the other poster being strident, who I was asking to play nice.

If you post a full issue with a clear reproduction we can probably help.

Haseeba393 commented 3 years ago

But if a person don't want to use any library for the splash screen?

On Thu, 18 Mar 2021 at 17:54, Mike Hardy @.***> wrote:

You actually should use a splash screen library if you want a splash screen, as they need native integration to show while the js bundle boots, which is a big part of app startup time.

It was the other poster being strident, who I was asking to play nice.

If you post a full issue with a clear reproduction we can probably help.

β€” You are receiving this because you commented. Reply to this email directly, view it on GitHub https://github.com/invertase/react-native-firebase/issues/3964#issuecomment-801901210, or unsubscribe https://github.com/notifications/unsubscribe-auth/AJ3R4UGKM26EOZCYWLFSENTTEHZYXANCNFSM4O6E2GLQ .

mikehardy commented 3 years ago

Then don't, I just explained why you might want to, with a specific reason. Your choice of course.

The rest of my comment stands.

Haseeba393 commented 3 years ago

Thank you very much for your response.

On Thu, 18 Mar 2021 at 18:16, Mike Hardy @.***> wrote:

Then don't, I just explained why you might want to, with a specific reason. Your choice of course.

The rest of my comment stands.

β€” You are receiving this because you commented. Reply to this email directly, view it on GitHub https://github.com/invertase/react-native-firebase/issues/3964#issuecomment-801917541, or unsubscribe https://github.com/notifications/unsubscribe-auth/AJ3R4UG6D5SQX6RRKH5CPFTTEH4JDANCNFSM4O6E2GLQ .

Haseeba393 commented 3 years ago

I have solved the problem. It's really a minor problem that took too long to solve. The getInitialNotification() is returning a promise and inside the promise callback, we can access that notification. What I was doing, I'm using the callback inside the above method which is not returning anything. Thank you everyone for helping me out.

sadafliaqat2nov commented 3 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:

{
  "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

Android

Click To Expand

Environment

Click To Expand

did you get any solution to this error?

Haseeba393 commented 3 years ago

@sadafliaqat2nov Can you please show me how you are using this method messaging().getInitialNotification() in your code?

sadafliaqat2nov commented 3 years ago

@Haseeba393

// It will trigger when app was in background
    messaging().onNotificationOpenedApp((remoteMessage) => {
      alert(JSON.stringify(remoteMessage));
    });

    // It will trigger when app will opened after trigger background notification
    messaging().setBackgroundMessageHandler(async (remoteMessage) => {
      alert(JSON.stringify(remoteMessage));
    });

    // It will trigger when app was in quit mode
    messaging().getInitialNotification(async (remoteMessage) => {
      alert(JSON.stringify(remoteMessage));
    });

    // If App is in foreground mode
    messaging().onMessage((remoteMessage) => {
      alert(JSON.stringify(remoteMessage.notification.body));
    });
I'm using these listeners in App.js
Haseeba393 commented 3 years ago

Okay, i also encountered this issue a few days ago. messaging().getInitialNotification() is not a callback, it is promise actually. so just replace your messaging().getInitialNotification() listener with this: messaging().getInitialNotification().then((remoteNotification)=>{ // do whatever you want to here }) .catch((err)=>{ alert(err); })

sadafliaqat2nov commented 3 years ago

@Haseeba393 Yesss, now it's working fine. Thankyou!

Haseeba393 commented 3 years ago

your welcome.

prasanthvenkatachalam commented 3 years ago

Thanks a lot. it worked

prasanthvenkatachalam commented 3 years ago

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();
    }
}

Thanks a lot. it worked

mikehardy commented 3 years ago

Use react-native-boot-splash

rostyk-kanafotskyy commented 3 years ago

This helped me #4005

martinGM05 commented 2 years ago

I was able to solve this problem, helping me with the notifee. I work with React Native and this library can listen to the events of your notifications.

kirannk-1306 commented 2 years ago

intent.putExtras(getIntent().getExtras());

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",

Hi @RishavKumar-3796, I am facing the same issue, When there are multiple notifications, if i close the app and click on notification, Data is empty. Kindly let me know if you had any solutions/ workarounds. Thanks.

fukemy commented 2 years ago

still not working to me

fukemy commented 2 years ago

messaging().onNotificationOpenedApp called even when app killed + i got fcm notification?? ( Android)

nugrohoaaldi commented 2 years ago

Okay, i also encountered this issue a few days ago. messaging().getInitialNotification() is not a callback, it is promise actually. so just replace your messaging().getInitialNotification() listener with this: messaging().getInitialNotification().then((remoteNotification)=>{ // do whatever you want to here }) .catch((err)=>{ alert(err); })

its work for me thank you πŸ˜πŸ‘

meta-utkarsh-ahuja commented 1 year ago

hi i have created nested navigation how can is use this when i am using drawer screen it is givng error // *Logout Functionality Starts*****//

// function for handling log out const handleLogOutPress = async () => { try { setShowLoader(true); GoogleSignin.configure(); const response = await usersService.logOut(); console.log(response.data, 'response from logout api'); if (response != undefined && response.data != undefined) { const logOutResponse = response.data.status; if (logOutResponse) { const data = { id: '', name: '', image: '', email: '', gender: '', contact: '', employeeId: '', role: '', drivingLicence: '', isLoggedIn: false, isTermAccepted: true, }; dispatch(setUserData(data));

      // handle success response here
      navigation.reset({
        index: 0,
        routes: [{name: 'GoogleSignInScreen'}],
      });
      GoogleSignin.signOut()
        .then(resp => {
          console.log(resp, 'response from google signout ');
        })
        .catch(error => {
          console.log(error, 'error in google sign out');
        });

      clearAsyncStorage()
        .then(() => {
          console.log('cleared successfully');
        })
        .catch(error => {
          console.log(error, 'error in clearing');
        });

      saveInLocal(strings.LOGOUT_KEY, 'true')
        .then(() => {
          console.log('saved successfully');
        })
        .catch(error => {
          console.log(error, 'error in clearing');
        });
      Toast.show({
        type: 'success',
        text1: strings.SignOut,
        text2: strings.SignOutMessage,
        visibilityTime: 2000,
      });
    }
  }
} catch (error) {
  console.log(error, 'error in logout api');
  handleApiError(error, navigation);
} finally {
  setShowLoader(false);
}

};

// function for showing logout modal const showLogoutModal = () => { setShowModal(true); };

// function for hiding logout modal const hideLogoutModal = () => { setShowModal(false); };

// *Logout Functionality Ends*****//

const currentUserName = useSelector(state => state.user.name); const currentUserImage = useSelector(state => state.user.image); // returning custom drawer return ( <DrawerContentScrollView {...props}>

{currentUserImage ? ( ) : ( )} {currentUserName}
  <DrawerItemList {...props} />

  {/*Logout UI Starts  */}
  <DrawerItem
    label="Sign Out"
    onPress={showLogoutModal}
    icon={() => <AntDesign name="logout" size={24} color={'black'} />}
  />
  <Popup
    isVisible={showModal}
    onConfirm={handleLogOutPress}
    text={'Are you sure you want to sign out?'}
    onCancel={hideLogoutModal}
    showLoader={showLoader}
    confirmText={'Yes'}
    cancelText={'Cancel'}
  />
  {/* Version and Copyright Text */}
  <View style={{bottom: 0}}>
    <Text
      style={{
        marginVertical: 50,
        marginHorizontal: 16,
        fontSize: 14,
        color: 'grey',
      }}>
      Copyright Β©2023 Metacube{'\n'}All Rights Reserved. v0.1{' '}
    </Text>
  </View>

  {/*Logout UI Ends  */}
</DrawerContentScrollView>

); };

const HomeDrawer = ({navigation}) => { // Creating the Drawer component to be used in the HomeScreen const [unreadCount, setUnreadCount] = useState(0);

useEffect(() => { unreadNotification(); }, []);

useEffect(() => { const subscription = MyCustomEventEmitter.addListener( 'onNotification', () => { unreadNotification(); }, ); return () => { subscription.remove(); }; }, []);

// api call for reading all notification const unreadNotification = async () => { try { const resp = await usersService.getMyUnreadNotofication(); console.log(resp.data); if (resp.data.status) { setUnreadCount(resp.data.data); } } catch (error) {} };

const notificationIcon = () => { return ( <TouchableOpacity onPress={() => navigation.navigate('Notifications')} style={{marginRight: 10}}>

    {unreadCount > 0 && (
      <View
        style={{
          position: 'absolute',
          top: -5,
          right: -5,
          backgroundColor: 'red',
          alignItems: 'center',
          justifyContent: 'center',
          width: 18,
          height: 18,
          borderRadius: 9,
        }}>
        <Text style={{color: 'white', fontSize: 12}}>{unreadCount}</Text>
      </View>
    )}
  </TouchableOpacity>
);

};

// get current user role const currentUserRole = useSelector(state => state.user.role); // home name const homeName = useSelector(state => state.home.name); return ( <Drawer.Navigator initialRouteName="HomeScreen" screenOptions={{ headerStyle: { backgroundColor: '#3698ce', }, headerTintColor: 'white', headerTitleStyle: { fontSize: 20, }, }} drawerContent={props => <CustomDrawerContent {...props} />}> <Drawer.Screen name="Home" component={HomeScreen} options={({navigation}) => ({ headerRight: () => notificationIcon(navigation),

      drawerIcon: ({focused}) => (
        <Ionicons name="home-outline" size={24} color={'black'} />
      ),
      headerTitle: homeName,
    })}
  />
  <Drawer.Screen
    name="Profile"
    component={Profile}
    options={({navigation}) => ({
      headerRight: () => notificationIcon(navigation),
      drawerIcon: ({focused}) => (
        <AntDesign name="profile" size={24} color={'black'} />
      ),
    })}
  />

  <Drawer.Screen
    name="Vehicle List"
    component={VehicleList}
    options={({navigation}) => ({
      headerRight: () => notificationIcon(navigation),
      drawerIcon: ({focused}) => (
        <AntDesign name="car" size={24} color={'black'} />
      ),
    })}
  />
  <Drawer.Screen
    name="My Rides"
    component={MyBookings}
    options={({navigation}) => ({
      headerRight: () => notificationIcon(navigation),
      drawerIcon: ({focused}) => (
        <Entypo name="list" size={24} color={'black'} />
      ),
    })}
  />

  <Drawer.Screen
    name="My Carpool"
    component={MyRides}
    options={({navigation}) => ({
      headerRight: () => notificationIcon(navigation),
      drawerIcon: ({focused}) => (
        <Ionicons name="people-outline" size={24} color={'black'} />
      ),
    })}
  />
  <Drawer.Screen
    name="Ride Requests"
    component={Requests}
    options={({navigation}) => ({
      headerRight: () => notificationIcon(navigation),
      drawerIcon: ({focused}) => (
        <Octicons name="checklist" size={25} color={'black'} />
      ),
    })}
  />

  <Drawer.Screen
    name="Contact Us"
    component={ContactUs}
    options={({navigation}) => ({
      headerRight: () => notificationIcon(navigation),
      drawerIcon: ({focused}) => (
        <AntDesign name="contacts" size={24} color={'black'} />
      ),
    })}
  />

  <Drawer.Screen
    name="Help"
    component={HelpSection}
    options={({navigation}) => ({
      headerRight: () => notificationIcon(navigation),
      drawerIcon: ({focused}) => (
        <Ionicons name="help-circle-outline" size={24} color={'black'} />
      ),
    })}
  />
  <Drawer.Screen
    name="Settings"
    component={NotificationToggle}
    options={({navigation}) => ({
      headerRight: () => notificationIcon(navigation),
      drawerIcon: ({focused}) => (
        <AntDesign name="setting" size={24} color={'black'} />
      ),
    })}
  />
  {currentUserRole == 1 ? (
    <Drawer.Screen
      name="SOS Alerts"
      component={SOSDetails}
      options={({navigation}) => ({
        headerRight: () => notificationIcon(navigation),
        drawerIcon: ({focused}) => (
          <MaterialCommunityIcons
            name="security"
            size={24}
            color={'black'}
          />
        ),
      })}
    />
  ) : (
    <></>
  )}
</Drawer.Navigator>

); };

const StackNavigator = () => { const navigation = useNavigation(); const [status, setStatus] = useState(''); useEffect(() => { // Assume a message-notification contains a "type" property in the data payload of the screen to open

messaging().onNotificationOpenedApp(remoteMessage => {
  console.log(
    'Notification caused app to open from background state: *********************************',
    remoteMessage,
    remoteMessage.data.type,
  );
  setStatus(remoteMessage.data.type);
  let getStatus = status;
  switch (getStatus) {
    case 2:
      navigation.navigate('My Rides');
      break;
    case 5:
      navigation.navigate('My Rides');
      break;
    case 6:
      navigation.navigate('My Rides');
      break;
    case 1:
      navigation.navigate('Ride Requests');
      break;
    case 9:
      navigation.navigate('SOS Alerts');
      break;
    case 8:
      navigation.navigate('My Rides');
      break;
    default:
      navigation.navigate('SOS Alerts');
  }
});
messaging()
  .getInitialNotification()
  .then(remoteMessage => {
    if (remoteMessage) {
      console.log(
        '*********************Notification caused app to open from quit state:******************',
        remoteMessage,
      );
       navigation.navigate('SplashScreen',{ nextPage : 'My Rides'});
    }

  });

}, []); return ( <Stack.Navigator //Passing Props to for header initialRouteName='My' screenOptions={{ headerTintColor: 'white', // set the header color to blue headerStyle: { backgroundColor: '#3698ce', // set the background color of the header fontSize: 20, // set the font size of the header title }, }}> <Stack.Screen name="SplashScreen" component={SplashScreen} options={{headerShown: false}} /> <Stack.Screen name="AvailableRides" component={AvailableRides} options={{title: 'Available Rides'}} />

  <Stack.Screen
    name="OfferedRideDetail"
    component={OfferRidePublish}
    options={{title: 'Offered Ride Details'}}
  />

  <Stack.Screen
    name="Booking Detail"
    component={BookingDetail}
    options={{title: 'Booking Details'}}
  />

  {/* <Stack.Screen
    name="MyRides"
    component={MyRides}
    // options={{ headerShown: false }}
    options={{ title: "My Rides" }}
  /> */}

  <Stack.Screen
    name="Chat"
    component={Chat}
    options={{title: 'Messages'}}
  />

  <Stack.Screen
    name="GoogleSignInScreen"
    component={GoogleSignInScreen}
    options={{headerShown: false}}
  />

  <Stack.Screen
    name="HomeScreen"
    // Using Home Screen For initailising Drawer
    component={HomeDrawer}
    options={{headerShown: false}}
  />

  <Stack.Screen
    name="Schedule"
    component={Schedule}
    options={{title: 'Scheduled Ride'}}
  />
  <Stack.Screen
    name="SearchRide"
    component={SearchRide}
    options={{title: 'SearchRide'}}
  />
  {/* <Stack.Screen name="VehicleList" component={VehicleList} options={{ title: 'SearchRide' }} /> */}
  <Stack.Screen
    name="StopOver"
    component={SelectStopOvers}
    options={{title: strings.Create_Ride}}
  />
  <Stack.Screen
    name="AddedVehicleList"
    component={AddedVehicleList}
    options={{title: 'Select Your Vehicle'}}
  />

  <Stack.Screen
    name="PublishRide"
    component={PublishRide}
    options={{title: 'Create  Ride'}}
  />

  <Stack.Screen
    name="SelectStopOvers"
    component={SelectStopOvers}
    options={{title: 'Create Ride '}}
  />

  <Stack.Screen
    name="AddVehicle"
    component={AddVehicle}
    options={{title: 'Add Vehicle'}}
  />

  <Stack.Screen
    name="RepeatRideRequestList"
    component={RepeatRideRequestList}
    options={{title: 'Ride Request List'}}
  />
  <Stack.Screen
    name="HelpSectionDetails"
    component={HelpSectionDetails}
    options={{
      title: '',
    }}
  />

  <Stack.Screen
    name="Profiles"
    component={Profile}
    options={{title: 'Profile'}}
  />

  <Stack.Screen
    name="ScheduleBooking"
    component={ScheduleBooking}
    options={{title: 'Scheduled Ride Booking'}}
  />
  <Stack.Screen
    name="RideDetail"
    component={RideDetail}
    options={{title: 'My Carpool Details'}}
  />
  <Stack.Screen name="Notifications" component={Notification} />
</Stack.Navigator>

); };

export default StackNavigator;

const styles = StyleSheet.create({ profileContainer: { alignItems: 'center', justifyContent: 'center', paddingTop: 10, // paddingVertical: 30, }, profileImageContainer: { height: 80, width: 80, borderRadius: 60, overflow: 'hidden', }, profileImage: { height: '100%', width: '100%', }, profileTextContainer: { marginTop: 10, alignItems: 'center', }, profileName: { fontSize: 16, fontWeight: 'bold', }, });