Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

getInitialNotification not working #3964

Closed
2 of 10 tasks
ghasemikasra39 opened this issue Jul 17, 2020 · 71 comments
Closed
2 of 10 tasks

getInitialNotification not working #3964

ghasemikasra39 opened this issue Jul 17, 2020 · 71 comments
Labels
platform: ios Type: Stale Issue has become stale - automatically added by Stale bot

Comments

@ghasemikasra39
Copy link

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
  • 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
    • 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
Copy link
Collaborator

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
Copy link
Author

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
Copy link
Collaborator

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
Copy link
Author

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
Copy link
Author

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
Copy link

Suresh-R-S commented Jul 20, 2020

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

@ghasemikasra39
Copy link
Author

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
Copy link

Suresh-R-S commented Jul 20, 2020

@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
Copy link
Author

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
Copy link

Suresh-R-S commented Jul 20, 2020

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
Copy link
Author

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

@ghasemikasra39
Copy link
Author

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
Copy link

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

@ghasemikasra39
Copy link
Author

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

@ghasemikasra39
Copy link
Author

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

@stale
Copy link

stale bot commented Sep 7, 2020

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 stale bot added the Type: Stale Issue has become stale - automatically added by Stale bot label Sep 7, 2020
@maduraherath8

This comment has been minimized.

@stale stale bot removed the Type: Stale Issue has become stale - automatically added by Stale bot label Sep 22, 2020
@mikehardy

This comment has been minimized.

@thang-nm
Copy link

@ghasemikasra39 Did you resolve your problem?

@metwal14
Copy link

metwal14 commented Nov 9, 2020

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
Copy link
Collaborator

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 crazycodeboy/react-native-splash-screen#289 (comment)

@RishavKumar-3796
Copy link

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
Copy link

stale bot commented Dec 18, 2020

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.

@prasanthvenkatachalam
Copy link

prasanthvenkatachalam commented May 8, 2021

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
Copy link
Collaborator

Use react-native-boot-splash

@rostyk-kanafotskyy
Copy link

This helped me #4005

@martinGM05
Copy link

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
Copy link

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
Copy link

fukemy commented Sep 26, 2022

still not working to me

@fukemy
Copy link

fukemy commented Sep 26, 2022

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

@nugrohoaaldi
Copy link

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
Copy link

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 ? (
<Image
style={styles.profileImage}
source={{
uri: currentUserImage,
}}
/>
) : (
<Image
style={styles.profileImage}
source={require('../assets/images/profileImage.png')}
/>
)}


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

)}

);
};

// 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',
},
});

@keshavsharma0712
Copy link

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
Copy link

@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
Copy link

surya-dharmakrishnan commented Sep 26, 2023

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
Copy link

khushbujilka22 commented Sep 30, 2023

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
Copy link

facing this issue. can anybody help?

@Haseeba393
Copy link

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

@thisisashukla
Copy link

@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
Copy link

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

@thisisashukla
Copy link

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

@Haseeba393
Copy link

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

@thisisashukla
Copy link

react native expo

@Haseeba393
Copy link

testing on real device or emulator?

@khanakia
Copy link

khanakia commented Dec 9, 2023

@thisisashukla were you able to make it work ?

@thisisashukla
Copy link

@thisisashukla were you able to make it work ?

Yes

@khanakia
Copy link

khanakia commented Dec 9, 2023

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
Copy link

tao-qian commented Jan 10, 2024

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
Copy link

khanakia commented Jan 10, 2024

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
Copy link

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:

  • notifee.onForegroundEvent(), which seems to be triggering in foreground, background and quit state on iOS (not sure why)
  • notifee.onBackground(), which seems to be triggering in background state on Android
  • notifee.getInitialNotification(), which seems to be triggering in quit state on Android

@autimio
Copy link

autimio commented Jul 5, 2024

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
Copy link

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
Copy link

This works for me

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
platform: ios Type: Stale Issue has become stale - automatically added by Stale bot
Projects
None yet
Development

No branches or pull requests