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

Receiving message when app clossed but unable to receive notification while App is in foreground. #3562

Closed nlimbu closed 4 years ago

nlimbu commented 4 years ago

Issue

Hi,

I have been stuck with this issue for a while. I believe the setup has been done correctly as per the documentation on 5.x.x deprecated site. I am able to receive the notification from both the Firebase Console and via the app server only while the app is closed. I am able to read the notification on app start via firebase.notifications().getInitialNotification().

On App.js (componentDidMount):

firebase.messaging().hasPermission()
    .then(enabled => {
        if (!enabled) {
            firebase.messaging().requestPermission()
                .then(() => {
                    this.addFcmListeners()
                })
                .catch(() => {
                })
        } else {
            this.addFcmListeners()
        }
})

addFcmListeners:

addFcmListeners = () => {
    this.removeTokenRefreshListener = firebase.messaging().onTokenRefresh(this.checkFcmToken);
    this.notificationReceived = firebase.notifications().onNotification((notification) => {
        console.log(`%c onNotification: `, 'color:green;', notification)
    });
    this.onNotificationDisplayed = firebase.notifications().onNotificationDisplayed((notification) => {
        console.log(`%c onNotification displayed: `, 'color:green;', notification)
    });
    this.onNotificationOpened = firebase.notifications().onNotificationOpened((notification) => {
        console.log(`%c onNotification opened: `, 'color:green;', notification)
    });

    this.messageListener = firebase.messaging().onMessage((notification) => {
        console.log(`%c onNotification Received: `, `color:green;`, notification)
        this.props.notificationReceived()
    });
}

It seemed as if the notification module was not functional at all but on the other hand, I am able to read them on firebase.notifications().getInitialNotification(). Thanks for reading. Any assistance much appreciated.


Project Files

Javascript

Click To Expand

#### `package.json`: ```json { "name": "AwesomeApp", "version": "0.0.1", "private": true, "scripts": { "start": "node node_modules/react-native/local-cli/cli.js start", }, "dependencies": { "@babel/preset-react": "^7.0.0", "@react-native-community/async-storage": "^1.6.2", "@react-native-community/audio-toolkit": "https://github.com/ssg-luke/react-native-audio-toolkit#tone-and-sculpt", "@react-native-community/netinfo": "^5.3.1", "@redux-offline/redux-offline": "^2.5.1", "axios": "^0.18.1", "bugsnag-react-native": "~2.22.6", "currency-symbol-map": "^4.0.4", "fractional": "^1.0.0", "immer": "^1.8.0", "inputmask-core": "^2.2.0", "jwt-decode": "^2.2.0", "lodash": "^4.17.15", "lottie-react-native": "^2.5.10", "moment": "^2.23.0", "pluralize": "^7.0.0", "random-item": "^1.0.0", "react": "16.8.3", "react-native": "0.59.10", "react-native-android-keyboard-adjust": "^1.2.0", "react-native-animatable": "^1.3.3", "react-native-background-timer": "^2.1.1", "react-native-branch": "https://github.com/ssg-luke/react-native-branch-deep-linking-attribution#toneandsculpt", "react-native-calendars": "https://github.com/SolidStateGroup/react-native-calendars#feature/header-ref", "react-native-camera": "^1.13.1", "react-native-cardview": "^2.0.2", "react-native-circular-progress": "^1.3.4", "react-native-code-push": "^5.6.0", "react-native-config": "^0.11.7", "react-native-confirmation-code-field": "^3.6.0", "react-native-device-info": "3.1.4", "react-native-devsettings-android": "^0.3.0", "react-native-draggable-flatlist": "^1.1.9", "react-native-easy-toast": "^1.1.0", "react-native-exit-app": "^1.0.0", "react-native-fbsdk": "^0.8.0", "react-native-firebase": "~5.6.0", "react-native-fs": "^2.13.3", "react-native-fullscreen-video": "0.0.9", "react-native-gesture-handler": "^1.1.0", "react-native-globals": "^0.59.0", "react-native-haptic-feedback": "^1.8.2", "react-native-iap": "^2.5.1", "react-native-image-pan-zoom": "^2.1.11", "react-native-image-picker": "^0.28.1", "react-native-image-resizer": "^1.0.1", "react-native-image-view": "^2.1.8", "react-native-interactable": "^1.0.0", "react-native-keyboard-aware-scroll-view": "^0.9.1", "react-native-linear-gradient": "^2.5.3", "react-native-loading-spinner-overlay": "^1.0.1", "react-native-mixpanel": "^1.1.4", "react-native-modal": "^11.5.3", "react-native-modal-datetime-picker": "^6.0.0", "react-native-onesignal": "^3.2.11", "react-native-permissions": "^1.1.1", "react-native-picker": "^4.3.7", "react-native-picker-select": "^5.1.0", "react-native-rate": "^1.1.10", "react-native-reanimated": "^1.2.0", "react-native-render-html": "^4.1.1", "react-native-screenshot-detector": "^1.0.0", "react-native-share": "^2.0.0", "react-native-svg": "^9.2.4", "react-native-swipe-gestures": "^1.0.4", "react-native-swiper": "^1.5.14", "react-native-swiper-gestures": "https://github.com/SolidStateGroup/react-native-swiper#gesture-handling", "react-native-switch-selector": "^1.1.12", "react-native-tab-view": "^2.10.0", "react-native-vector-icons": "^6.1.0", "react-native-video": "https://github.com/SolidStateGroup/react-native-video#tone-and-sculpt", "react-native-view-pdf": "^0.6.3", "react-native-view-shot": "^2.5.0", "react-native-waveview": "^1.1.0", "react-navigation": "^3.9.1", "react-navigation-animated-switch": "^0.3.2", "react-redux": "^5.1.1", "reanimated-bottom-sheet": "^1.0.0-alpha.16", "redux": "^4.0.1", "redux-persist": "^5.10.0", "redux-thunk": "^2.3.0", "rn-fetch-blob": "^0.10.14", "save": "^2.3.3", "uuid": "^3.3.2", "words-to-numbers": "^1.5.1" }, "devDependencies": { "@babel/core": "^7.4.5", "@babel/runtime": "^7.4.5", "@react-native-community/eslint-config": "^0.0.5", "babel-jest": "^24.7.1", "babel-plugin-jsx-control-statements": "^4.0.0", "babel-plugin-meaningful-logs": "^1.0.2", "babel-plugin-module-resolver": "^3.2.0", "babel-plugin-transform-remove-console": "^6.9.4", "babel-preset-react-optimize": "^1.0.1", "eslint": "^6.3.0", "eslint-import-resolver-babel-module": "^5.1.0", "jest": "^24.7.1", "jetifier": "^1.6.4", "metro-react-native-babel-preset": "^0.54.1", "prettier": "^1.18.2", "react-native-linknopod": "^2.0.1", "react-test-renderer": "16.8.3" }, "jest": { "preset": "react-native" }, "rnpm": { "assets": [ "./assets/fonts/" ] } } ``` #### `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 # Uncomment the next line to define a global platform for your project platform :ios, '9.0' def my_pods pod 'FBSDKCoreKit', '~> 4.40.0' pod 'FBSDKLoginKit', '~> 4.40.0' pod 'FBSDKShareKit', '~> 4.40.0' pod 'Branch' pod 'Mixpanel' pod 'Firebase/Core', '~> 6.3.0' pod 'Firebase/Messaging', '~> 6.3.0' end target 'awesomeApp' do # Uncomment the next line if you're using Swift or would like to use dynamic frameworks # use_frameworks! my_pods target 'awesomeAppTests' do inherit! :search_paths # Pods for testing end end ``` #### `AppDelegate.m`: ```objc #import "AppDelegate.h" #import #import #import #import #import #import #import #import #import #import #import "ReactNativeConfig.h" #import "RNFirebaseNotifications.h" #import "RNFirebaseMessaging.h" @implementation AppDelegate - (void)applicationDidBecomeActive:(UIApplication *)application { [FBSDKAppEvents activateApp]; } - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { [FIRApp configure]; [RNFirebaseNotifications configure]; [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient error:nil]; // allow [[FBSDKApplicationDelegate sharedInstance] application:application didFinishLaunchingWithOptions:launchOptions]; NSString *mixpanelToken = [ReactNativeConfig envFor:@"MIXPANEL_TOKEN"]; [Mixpanel sharedInstanceWithToken:mixpanelToken]; [RNBranch setRequestMetadataKey:@"$mixpanel_distinct_id" value:[Mixpanel sharedInstance].distinctId]; [RNBranch initSessionWithLaunchOptions:launchOptions isReferrable:YES]; RCTBridge *bridge = [[RCTBridge alloc] initWithDelegate:self launchOptions:launchOptions]; RCTRootView *rootView = [[RCTRootView alloc] initWithBridge:bridge moduleName:@"awesomeApp" initialProperties:nil]; rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f green:1.0f blue:1.0f alpha:1]; RNScreenshotDetector* screenshotDetector = [[RNScreenshotDetector alloc] init]; [screenshotDetector setupAndListen:rootView.bridge]; self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds]; UIViewController *rootViewController = [UIViewController new]; rootViewController.view = rootView; self.window.rootViewController = rootViewController; [self.window makeKeyAndVisible]; // Allow background audio playback [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient error:nil]; return YES; } - (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification { [[RNFirebaseNotifications instance] didReceiveLocalNotification:notification]; } - (void)application:(UIApplication *)application didReceiveRemoteNotification:(nonnull NSDictionary *)userInfo fetchCompletionHandler:(nonnull void (^)(UIBackgroundFetchResult))completionHandler{ [[RNFirebaseNotifications instance] didReceiveRemoteNotification:userInfo fetchCompletionHandler:completionHandler]; } - (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings { [[RNFirebaseMessaging instance] didRegisterUserNotificationSettings:notificationSettings]; } - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url options:(NSDictionary *)options { BOOL handled = YES; if (![RNBranch.branch application:application openURL:url options:options]) { handled = [[FBSDKApplicationDelegate sharedInstance] application:application openURL:url sourceApplication:options[UIApplicationOpenURLOptionsSourceApplicationKey] annotation:options[UIApplicationOpenURLOptionsAnnotationKey] ]; } return handled; } - (BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void (^)(NSArray *restorableObjects))restorationHandler { return [RNBranch continueUserActivity:userActivity]; } - (NSURL *)sourceURLForBridge:(RCTBridge *)bridge { #if DEBUG return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil]; #else return [CodePush bundleURL]; #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: (12) x64 Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz Memory: 185.66 MB / 16.00 GB Shell: 5.7.1 - /bin/zsh Binaries: Node: 13.2.0 - /usr/local/bin/node Yarn: 1.17.3 - /usr/local/bin/yarn npm: 6.14.4 - /usr/local/bin/npm Watchman: 4.9.0 - /usr/local/bin/watchman Managers: CocoaPods: 1.9.1 - /usr/local/bin/pod SDKs: iOS SDK: Platforms: iOS 13.4, DriverKit 19.0, macOS 10.15, tvOS 13.4, watchOS 6.2 Android SDK: Not Found IDEs: Android Studio: 3.5 AI-191.8026.42.35.5900203 Xcode: 11.4.1/11E503a - /usr/bin/xcodebuild Languages: Java: 12.0.2 - /usr/bin/javac Python: 2.7.16 - /usr/bin/python npmPackages: @react-native-community/cli: Not Found react: 16.8.3 => 16.8.3 react-native: 0.59.10 => 0.59.10 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:** - `5.6.0` - **`Firebase` module(s) you're using that has the issue:** - `Firebase/Messaging` - **Are you using `TypeScript`?** - `N`


nlimbu commented 4 years ago

To test further... I am using this script:

DEVICE="<DeviceToken>"
KEY="<Key>"
JSON="
  {
    \"to\": \"$DEVICE\",
    \"priority\":\"high\",
    \"notification\": {
            \"body\":\"Thi is a test message\",
            \"badge\": 8,
            \"data\":  {
                \"key_a\": \"Some text here\",
                \"key_b\": 656,
            },
    },
    \"data\": {
      \"key_a\": \"Some text here\",
      \"key_b\": 656,
    },
  }
"

curl -X POST \
  --header "Authorization: key=$KEY" \
  --Header "Content-Type: application/json" \
  https://fcm.googleapis.com/fcm/send \
  -d "$JSON"

Also observed by removing the notification from the JSON schema,

JSON="
  {
    \"to\": \"$DEVICE\",
    \"priority\":\"high\",
    \"data\": {
      \"key_a\": \"Some text here\",
      \"key_b\": 656,
    },
  }
"

I am able to receive it as RemoteMessage on firebase.messaging().onMessage but with this schema unable to receive notification when the app is closed.

EnettyTech commented 4 years ago

Same issue. My app receive notification worked on ios but not work when app is closed on android. How resolve??

technoknol commented 4 years ago

@nlimbu

While app in foreground, the message sent from the firebase-console/app-server is not being received on firebase.notifications().onNotification or anywhere.

When you're using an App and receive notification it won't display so you have to display it manually. This is called Local Notification, You'll find code for that for 5.x.x version.

emeraldsanto commented 4 years ago

This is also happening to me, everything works like a charm on Android but on iOS all notifications sent from the Firebase Console or HTTP API are received in the onMessage handler.

russellwheatley commented 4 years ago

Hey @nlimbu, thanks for your issue report. We’re no longer actively supporting <= v5 development so I’m going to go ahead and close this issue - but feel free to continue the discussion if required.

emeraldsanto commented 4 years ago

Fair enough, I've managed to upgrade to V6 rather quickly. I've tried to make react-native-notifications and react-native-push-notification work haven't had any success so far. Fortunately, I've also noticed my app doesn't need local notifications, native OS notifications and custom in-app toasts are more than enough so I ended up not needing any other library.