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.6k stars 2.19k forks source link

onMessage not getting called in IOS when the app is in foreground #6107

Closed manoj-makkuboy closed 1 year ago

manoj-makkuboy commented 2 years ago

Issue

onMessage is not being called when the app is foreground and receives remote message. This issue can be observed only in IOS and not in Android. If I do a hot reload of the app (The javascript metro bundler hot reload) it starts to work i.e.,. the onMessage is being called when the remote message is received.

FCM Payload

{
    "to": "[token]",
    "notification": {
        "title": "Check this Mobile (title)",
        "body": "Rich Notification testing (body)"
    },
    "data": {
        "key": "value"
    }
}
    "to": "[token]",
    "notification": {
        "title": "Check this Mobile (title)",
        "body": "Rich Notification testing (body)"
    },
    "data": {
        "key": "value"
    },
    "content_available":true
}

I tried logging inside the library I am able to see the flow passing through

[[RNFBRCTEventEmitter shared] sendEventWithName:@"messaging_message_received"
                                                 body:notificationDict];

But not seeing the listener const subscription = this.emitter.addListener('messaging_message_received', listener); in index.js getting executed.

import messaging from '@react-native-firebase/messaging';
class App extends Component {
constructor(props) {
    super(props);
    this.setupFirebaseNotification()
  }
   setupFirebaseNotification = async () => {
    let authStatus = await messaging().hasPermission(); //resolves successfully in android always
    let enabled =
    authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
    authStatus === messaging.AuthorizationStatus.PROVISIONAL;

    if (!enabled) {
      authStatus = await messaging().requestPermission();  //resolves successfully in android always
      enabled =
      authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
      authStatus === messaging.AuthorizationStatus.PROVISIONAL;
    }
    if(enabled){
      await messaging().registerDeviceForRemoteMessages();
      let fcmToken = await messaging().getToken();

      try{
        await AsyncStorage.setItem('deviceToken', fcmToken);
      }catch{
        console.log("error while storing fcm token")
      }

      messaging().onMessage((notification) => {
        console.log("onMessage called ()()()()()()()()(("); 
        this.onDisplayNotification(notification)
      });

      messaging().onNotificationOpenedApp((notification) => {
        console.log("onNotificationOpenedApp called ()()()()()()()()((");
        this.pushNotificationOnTapHandler(notification)
      })

      messaging().getInitialNotification().then((notification) => {
        console.log("getInitialNotification called ()()()()()()()()(("); this.pushNotificationOnTapHandler(notification)
      });

    }
  }
}

onMessage is not being called when the app is foreground and receives notification. This issue can be observed only in IOS and not in Android. If I do a hot reload of the app (The javascript metro bundler hot reload) it starts to work i.e.,. the onMessage is being called when the notification is received.


Project Files

Javascript

Click To Expand

#### `package.json`: ```json { "name": "[app_name]", "version": "2.4.8", "build": "2.4.8", "private": true, "scripts": { "android": "react-native run-android", "ios": "react-native run-ios", "start": "react-native start", "build-prod-android": "npx react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res && rm -rf android/app/src/main/res/drawable-* && rm -rf android/app/src/main/res/raw/*", "buildProductionApk": " cd android && ENVFILE=.env.production ./gradlew assembleRelease", "buildProductionBundle": " cd android && ENVFILE=.env.production ./gradlew bundleRelease", "buildStagingApk": " cd android && ENVFILE=.env.staging ./gradlew assembleRelease", "build-prod-ios": "npx react-native bundle --entry-file='index.js' --bundle-output='./ios/line_app/main.jsbundle' --dev=false --platform='ios' --assets-dest='./ios'", "test": "jest", "postinstall": "npx jetify", "lint": "eslint ." }, "dependencies": { "@apollo/react-hooks": "^4.0.0", "@notifee/react-native": "^4.1.0", "@ptomasroos/react-native-multi-slider": "^2.2.2", "@react-native-community/async-storage": "^1.12.0", "@react-native-community/blur": "^3.6.0", "@react-native-community/clipboard": "^1.5.1", "@react-native-community/masked-view": "^0.1.10", "@react-native-community/netinfo": "^6.0.0", "@react-native-community/viewpager": "^4.1.6", "@react-native-firebase/analytics": "^13.1.0", "@react-native-firebase/app": "^13.1.0", "@react-native-firebase/crashlytics": "^13.1.0", "@react-native-firebase/dynamic-links": "^13.1.0", "@react-native-firebase/messaging": "^13.1.0", "@react-native-firebase/ml": "^13.1.0", "@twotalltotems/react-native-otp-input": "^1.3.11", "Socure-DeviceRisk-React-sdk": "git+https://[key]:x-oauth-basic@github.com/socure-inc/Socure-DeviceRisk-React-sdk.git", "apollo-cache-inmemory": "^1.6.6", "apollo-client": "^2.6.10", "apollo-link-context": "^1.0.20", "apollo-link-http": "^1.5.17", "assert": "^1.1.1", "axios": "^0.20.0", "babel-plugin-module-resolver": "^4.1.0", "babel-plugin-transform-remove-console": "^6.9.4", "browserify-zlib": "~0.1.4", "buffer": "^4.9.1", "console-browserify": "^1.1.0", "constants-browserify": "^1.0.0", "dns.js": "^1.0.1", "domain-browser": "^1.1.1", "email-validator": "^2.0.4", "events": "^1.0.0", "fbemitter": "^2.1.1", "graphql": "^15.3.0", "https-browserify": "~0.0.0", "intl": "^1.2.5", "jail-monkey": "^2.3.2", "jsc-android": "^241213.1.0", "jscrambler-metro-plugin": "5.5.27", "lodash": "^4.17.20", "lodash.debounce": "^4.0.8", "lodash.get": "4.4.2", "lodash.uniqby": "^4.7.0", "mixpanel-react-native": "^1.3.4", "moment": "^2.27.0", "path-browserify": "0.0.0", "process": "^0.11.0", "public-ip": "^4.0.2", "punycode": "^1.2.4", "querystring-es3": "~0.2.0", "react": "16.13.1", "react-gauge-chart": "^0.3.0", "react-native": "0.63.3", "react-native-aes-crypto": "^1.3.9", "react-native-animated-ruler": "^1.1.1", "react-native-base64": "^0.1.0", "react-native-branch": "^5.0.0", "react-native-calendar-strip": "^2.0.9", "react-native-calendars": "^1.403.0", "react-native-camera": "^3.39.0", "react-native-confetti": "^0.1.0", "react-native-confetti-cannon": "^1.5.1", "react-native-config": "^1.4.5", "react-native-countdown-component": "^2.7.1", "react-native-credit-card-input": "^0.4.1", "react-native-datepicker": "^1.7.2", "react-native-device-info": "^8.0.8", "react-native-email-link": "^1.10.0", "react-native-exit-app": "^1.1.0", "react-native-fbsdk-next": "^6.1.1", "react-native-fs": "^2.16.6", "react-native-gesture-handler": "^1.8.0", "react-native-google-places": "^3.1.2", "react-native-image-crop-picker": "^0.34.1", "react-native-in-app-review": "^3.1.1", "react-native-indicators": "^0.17.0", "react-native-intercom": "21.1.1", "react-native-keyboard-aware-scroll-view": "^0.9.3", "react-native-keyboard-height": "^1.1.2", "react-native-keyboard-manager": "^4.0.13-16", "react-native-keychain": "^6.2.0", "react-native-level-fs": "^3.0.0", "react-native-linear-gradient": "^2.5.6", "react-native-network-info": "^5.2.1", "react-native-offline": "^5.7.0", "react-native-plaid-link-sdk": "7.0.5", "react-native-progress": "^4.1.2", "react-native-reanimated": "^1.13.0", "react-native-safe-area-context": "^3.1.7", "react-native-screens": "^2.10.1", "react-native-share": "^4.0.1", "react-native-size-matters": "^0.3.1", "react-native-skeleton-placeholder": "^3.0.4", "react-native-smooth-pincode-input": "^1.0.9", "react-native-snap-carousel": "^3.9.1", "react-native-speedometer-chart": "^0.7.5", "react-native-splash-screen": "^3.2.0", "react-native-svg": "^12.1.0", "react-native-svg-charts": "^5.4.0", "react-native-timeago": "^0.5.0", "react-native-touch-id": "^4.4.1", "react-native-user-inactivity": "^1.1.0", "react-native-version-check": "^3.4.2", "react-native-video": "^5.1.1", "react-native-view-shot": "^3.1.2", "react-native-webview": "^10.8.3", "react-navigation": "^4.4.0", "react-navigation-hooks": "^1.1.0", "react-navigation-stack": "^2.8.2", "readable-stream": "1.0.33", "rn-fetch-blob": "^0.12.0", "sift-react-native": "^0.1.1", "socure-ios-sdk": "git+https://[key]:x-oauth-basic@github.com/socure-inc/socure-ios-sdk.git", "stream-browserify": "^1.0.0", "string_decoder": "~0.10.25", "styled-components": "^5.2.0", "timers-browserify": "^1.0.1", "tty-browserify": "0.0.0", "url": "~0.10.1", "utf8": "^3.0.0", "util": "~0.10.3", "vm-browserify": "0.0.4", "xor-crypt": "^1.1.1" }, "resolutions": { "@apollo/client": "3.4.6" }, "devDependencies": { "@babel/core": "^7.8.4", "@babel/runtime": "^7.8.4", "@react-native-community/eslint-config": "^1.1.0", "babel-jest": "^25.1.0", "eslint": "^6.5.1", "jest": "^25.1.0", "metro-react-native-babel-preset": "^0.59.0", "react-test-renderer": "16.13.1" }, "jest": { "preset": "react-native" } } ``` #### `firebase.json` for react-native-firebase v6: ```json { "react-native": { "ml_vision_face_model": true, "crashlytics_debug_enabled": false, "crashlytics_auto_collection_enabled": false, "crashlytics_ndk_enabled": false, "messaging_ios_auto_register_for_remote_messages": false } }```

iOS

Click To Expand

#### `ios/Podfile`: - [x] I'm not using Pods - [] I'm using Pods and my Podfile looks like: require_relative '../node_modules/react-native/scripts/react_native_pods' require_relative '../node_modules/@react-native-community/cli-platform-ios/native_modules' plugin 'cocoapods-user-defined-build-types' platform :ios, '12.1' enable_user_defined_build_types! use_modular_headers! post_install do |installer| installer.pods_project.build_configurations.each do |config| config.build_settings["EXCLUDED_ARCHS[sdk=iphonesimulator*]"] = "arm64" installer.pods_project.targets.each do |target| target.build_configurations.each do |config| config.build_settings.delete 'IPHONEOS_DEPLOYMENT_TARGET' end end end end target 'line_app' do config = use_native_modules! use_react_native!(:path => config["reactNativePath"]) # Socure setup # pod 'Alamofire' pod 'PoweredByDosh', '~> 2.7.0' pod 'PoweredByDosh/DoshCardVaulting' pod "SwiftyJSON", :build_type => :dynamic_framework # Pods for SocureSdkDemo pod 'DeviceRisk', :build_type => :dynamic_framework, :path => '../node_modules/socure-ios-sdk' pod 'react-native-device-risk', :path => '../node_modules/Socure-DeviceRisk-React-sdk' pod 'react-native-intercom', :path => '../node_modules/react-native-intercom' # pod 'Plaid', '~> 2.3.2' pod 'react-native-plaid-link-sdk', :path => '../node_modules/react-native-plaid-link-sdk' pod 'react-native-view-shot', :path => '../node_modules/react-native-view-shot' pod 'RNShare', :path => '../node_modules/react-native-share' pod 'RNFS', :path => '../node_modules/react-native-fs' pod 'RNCMaskedView', :path => '../node_modules/@react-native-community/masked-view' pod 'glog', :podspec => '../node_modules/react-native/third-party-podspecs/glog.podspec', :modular_headers => false pod 'Folly', :podspec => '../node_modules/react-native/third-party-podspecs/Folly.podspec', :modular_headers => false pod 'react-native-version-check', :path => '../node_modules/react-native-version-check' pod 'VGSCollectSDK', "1.9.5" pod 'VGSCollectSDK/CardIO', "1.9.5" pod 'react-native-branch', path: '../node_modules/react-native-branch' target 'line_appTests' do inherit! :complete # Pods for testing end # Enables Flipper # # Note that if you have use_frameworks! enabled, Flipper will not work and # you should disable these next few lines. # use_flipper! # post_install do |installer| # flipper_post_install(installer) # end end target 'line_app-tvOS' do # Pods for line_app-tvOS target 'line_app-tvOSTests' do inherit! :search_paths # Pods for testing end end ```ruby # N/A ``` #### `AppDelegate.m`: ```objc #import "AppDelegate.h" #import #import "Intercom/intercom.h" #import #import #import #import #import #import #import @import GooglePlaces; @import GoogleMaps; @import Firebase; #import "ReactNativeConfig.h" @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { NSString *environment = [ReactNativeConfig envFor:@"ENVIRONMENT"]; [RNBranch initSessionWithLaunchOptions:launchOptions isReferrable:YES]; // <-- add this [[FBSDKApplicationDelegate sharedInstance] application:application didFinishLaunchingWithOptions:launchOptions]; [Intercom setApiKey:@"[apikey]" forAppId:@"[appid]"]; NSString * target = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleName"]; NSString *filePath; if([environment isEqual: @"production"]) { filePath = [[NSBundle mainBundle] pathForResource:@"GoogleService-Info" ofType:@"plist"]; } else { filePath = [[NSBundle mainBundle] pathForResource:@"GoogleService-Info_Dev" ofType:@"plist"]; } NSLog(@"File Path %@",filePath); FIROptions *options = [[FIROptions alloc] initWithContentsOfFile:filePath]; [FIRApp configureWithOptions:options]; NSString * googleKey =@"[googlekey]" ; [GMSPlacesClient provideAPIKey:googleKey]; [GMSServices provideAPIKey:googleKey]; RCTBridge *bridge = [[RCTBridge alloc] initWithDelegate:self launchOptions:launchOptions]; RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:[self sourceURLForBridge:bridge] moduleName:@"line_app" initialProperties:nil launchOptions:launchOptions]; rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f green:1.0f blue:1.0f alpha:1]; self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds]; UIViewController *rootViewController = [UIViewController new]; rootViewController.view = rootView; self.window.rootViewController = rootViewController; self.window.backgroundColor = [UIColor blackColor]; [self.window makeKeyAndVisible]; [RNSplashScreen show]; return YES; } - (NSURL *)sourceURLForBridge:(RCTBridge *)bridge { #if DEBUG NSLog(@"DEBUG"); return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil]; #else NSLog(@"RELEASE"); return [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"]; #endif } - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url options:(NSDictionary *)options { return [RCTLinkingManager application:application openURL:url options:options]; } // Only if your app is using [Universal Links](https://developer.apple.com/library/prerelease/ios/documentation/General/Conceptual/AppSearch/UniversalLinks.html). - (BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void (^)(NSArray * _Nullable))restorationHandler { return [RNBranch continueUserActivity:userActivity]; } - (void)goToLine { [self.window.rootViewController dismissViewControllerAnimated:TRUE completion:nil]; } @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 12.1 CPU: (8) x64 Apple M1 Memory: 23.80 MB / 8.00 GB Shell: 5.8 - /bin/zsh Binaries: Node: 14.19.0 - /usr/local/bin/node Yarn: 1.22.17 - /opt/homebrew/bin/yarn npm: 8.5.1 - /opt/homebrew/bin/npm Watchman: Not Found Managers: CocoaPods: 1.11.2 - /usr/local/bin/pod SDKs: iOS SDK: Platforms: DriverKit 21.2, iOS 15.2, macOS 12.1, tvOS 15.2, watchOS 8.3 Android SDK: API Levels: 28, 29, 30, 31, 32 Build Tools: 28.0.3, 29.0.2, 30.0.3, 32.0.0 System Images: android-31 | Google Play ARM 64 v8a, android-31 | Google Play Intel x86 Atom_64, android-32 | Google APIs ARM 64 v8a Android NDK: Not Found IDEs: Android Studio: 2020.3 AI-203.7717.56.2031.7935034 Xcode: 13.2.1/13C100 - /usr/bin/xcodebuild Languages: Java: 1.8.0_292 - /usr/bin/javac Python: 2.7.18 - /usr/bin/python npmPackages: @react-native-community/cli: Not Found react: 16.13.1 => 16.13.1 react-native: 0.63.3 => 0.63.3 react-native-macos: Not Found npmGlobalPackages: *react-native*: Not Found``` - **Platform that you're experiencing the issue on**: - [x] 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:** - `^13.1.0` - **`Firebase` module(s) you're using that has the issue:** - `e.g. Instance ID` - **Are you using `TypeScript`?** - `N` & `VERSION`


mikehardy commented 2 years ago

What happens when you use current stable of react-native and react-native-firebase? Your versions are a bit old here. Best would be a minimal repro based on https://github.com/mikehardy/rnfbdemo/blob/main/make-demo.sh with nothing but an App.js. Why? You would not believe the oddities I've seen happen from other packages interacting poorly, literally I've seen Promise behavior broken. Your package dependency list is too big to troubleshoot, so isolate react-native-firebase and test the onMessage functionality (as we do in our e2e testing) and it should work.

If you can still reproduce with a https://stackoverflow.com/help/minimal-reproducible-example and current versions then we can re-check

bilalahmad-gl commented 2 years ago

I was having this same issue. I do not know if it will work for you or not but for me, I this was occurred due to the "npm install" where I had to use "yarn".

After deleting node_modules, I just run "yarn install" and it worked.

stale[bot] commented 2 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.

github-actions[bot] commented 1 year 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 attention?

This issue will be closed in 15 days if no further activity occurs.

Thank you for your contributions.