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

🔥onMessage is Not Called when App is Opened by clicking the notification #3032

Closed
5 of 10 tasks
KTDevelopment opened this issue Dec 22, 2019 · 18 comments
Closed
5 of 10 tasks
Labels
plugin: messaging FCM only - ( messaging() ) - do not use for Notifications

Comments

@KTDevelopment
Copy link

KTDevelopment commented Dec 22, 2019

Issue

Describe your issue here

I managed to get messaging working when the App is in foreground, so registration for token and receiving works.
But there is a problem when opening the App from the notification.
The onMessage callback is not called if the App is opened that way.
What am I missing out, how can i achieve that i have a specific indicator if my app is opened from a Notification or even better how can i access the notification of that my app was opened from.

Project Files

Javascript

Click To Expand

package.json:

# N/A

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, '9.0'
require_relative '../node_modules/@react-native-community/cli-platform-ios/native_modules'

target 'AppName' do
  # Pods for AppName
  pod 'FBLazyVector', :path => "../node_modules/react-native/Libraries/FBLazyVector"
  pod 'FBReactNativeSpec', :path => "../node_modules/react-native/Libraries/FBReactNativeSpec"
  pod 'RCTRequired', :path => "../node_modules/react-native/Libraries/RCTRequired"
  pod 'RCTTypeSafety', :path => "../node_modules/react-native/Libraries/TypeSafety"
  pod 'React', :path => '../node_modules/react-native/'
  pod 'React-Core', :path => '../node_modules/react-native/'
  pod 'React-CoreModules', :path => '../node_modules/react-native/React/CoreModules'
  pod 'React-Core/DevSupport', :path => '../node_modules/react-native/'
  pod 'React-RCTActionSheet', :path => '../node_modules/react-native/Libraries/ActionSheetIOS'
  pod 'React-RCTAnimation', :path => '../node_modules/react-native/Libraries/NativeAnimation'
  pod 'React-RCTBlob', :path => '../node_modules/react-native/Libraries/Blob'
  pod 'React-RCTImage', :path => '../node_modules/react-native/Libraries/Image'
  pod 'React-RCTLinking', :path => '../node_modules/react-native/Libraries/LinkingIOS'
  pod 'React-RCTNetwork', :path => '../node_modules/react-native/Libraries/Network'
  pod 'React-RCTSettings', :path => '../node_modules/react-native/Libraries/Settings'
  pod 'React-RCTText', :path => '../node_modules/react-native/Libraries/Text'
  pod 'React-RCTVibration', :path => '../node_modules/react-native/Libraries/Vibration'
  pod 'React-Core/RCTWebSocket', :path => '../node_modules/react-native/'

  pod 'React-cxxreact', :path => '../node_modules/react-native/ReactCommon/cxxreact'
  pod 'React-jsi', :path => '../node_modules/react-native/ReactCommon/jsi'
  pod 'React-jsiexecutor', :path => '../node_modules/react-native/ReactCommon/jsiexecutor'
  pod 'React-jsinspector', :path => '../node_modules/react-native/ReactCommon/jsinspector'
  pod 'ReactCommon/jscallinvoker', :path => "../node_modules/react-native/ReactCommon"
  pod 'ReactCommon/turbomodule/core', :path => "../node_modules/react-native/ReactCommon"
  pod 'Yoga', :path => '../node_modules/react-native/ReactCommon/yoga'

  pod 'DoubleConversion', :podspec => '../node_modules/react-native/third-party-podspecs/DoubleConversion.podspec'
  pod 'glog', :podspec => '../node_modules/react-native/third-party-podspecs/glog.podspec'
  pod 'Folly', :podspec => '../node_modules/react-native/third-party-podspecs/Folly.podspec'

  target 'AppName' do
    inherit! :search_paths
    # Pods for testing
  end

  # 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'

  use_native_modules!
end

target 'AppName-tvOS' do
  # Pods for AppName-tvOS

  target 'AppName-tvOSTests' do
    inherit! :search_paths
    # Pods for testing
  end

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 "AppDelegate.h"

#import <React/RCTBridge.h>
#import <React/RCTBundleURLProvider.h>
#import <React/RCTRootView.h>
#import <GoogleMaps/GoogleMaps.h>
#import "RNBootSplash.h"
@import Firebase;

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  [GMSServices provideAPIKey:@"secret key"];
  if ([FIRApp defaultApp] == nil) {
    [FIRApp configure];
  }

  RCTBridge *bridge = [[RCTBridge alloc] initWithDelegate:self launchOptions:launchOptions];
  RCTRootView *rootView = [[RCTRootView alloc] initWithBridge:bridge
                                                   moduleName:@"AppName"
                                            initialProperties:nil];

  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 makeKeyAndVisible];
  [RNBootSplash show:@"LaunchScreen" inView:rootView];
  return YES;
}

- (NSURL *)sourceURLForBridge:(RCTBridge *)bridge
{
#if 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.properties jetifier=true for Android compatibility?
  • I am using the NPM package jetifier for react-native compatibility?

android/build.gradle:

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    ext {
        buildToolsVersion = "28.0.3"
        minSdkVersion = 21
        compileSdkVersion = 28
        targetSdkVersion = 28
        androidXCore = "1.0.2"
        supportLibVersion = "28.0.0"
        playServicesVersion = "17.0.0"
        androidMapsUtilsVersion = "0.6.2"
        // Put here other AndroidX dependencies
    }
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath("com.android.tools.build:gradle:3.4.2")

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
        classpath 'com.google.gms:google-services:4.2.0'
    }
}

allprojects {
    repositories {
        mavenLocal()
        maven {
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url("$rootDir/../node_modules/react-native/android")
        }
        maven {
            // Android JSC is installed from npm
            url("$rootDir/../node_modules/jsc-android/dist")
        }

        google()
        jcenter()
        maven { url 'https://jitpack.io' }
    }
}

android/app/build.gradle:

apply plugin: "com.android.application"

import com.android.build.OutputFile

/**
 * The react.gradle file registers a task for each build variant (e.g. bundleDebugJsAndAssets
 * and bundleReleaseJsAndAssets).
 * These basically call `react-native bundle` with the correct arguments during the Android build
 * cycle. By default, bundleDebugJsAndAssets is skipped, as in debug/dev mode we prefer to load the
 * bundle directly from the development server. Below you can see all the possible configurations
 * and their defaults. If you decide to add a configuration block, make sure to add it before the
 * `apply from: "../../node_modules/react-native/react.gradle"` line.
 *
 * project.ext.react = [
 *   // the name of the generated asset file containing your JS bundle
 *   bundleAssetName: "index.android.bundle",
 *
 *   // the entry file for bundle generation
 *   entryFile: "index.android.js",
 *
 *   // https://facebook.github.io/react-native/docs/performance#enable-the-ram-format
 *   bundleCommand: "ram-bundle",
 *
 *   // whether to bundle JS and assets in debug mode
 *   bundleInDebug: false,
 *
 *   // whether to bundle JS and assets in release mode
 *   bundleInRelease: true,
 *
 *   // whether to bundle JS and assets in another build variant (if configured).
 *   // See http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Build-Variants
 *   // The configuration property can be in the following formats
 *   //         'bundleIn${productFlavor}${buildType}'
 *   //         'bundleIn${buildType}'
 *   // bundleInFreeDebug: true,
 *   // bundleInPaidRelease: true,
 *   // bundleInBeta: true,
 *
 *   // whether to disable dev mode in custom build variants (by default only disabled in release)
 *   // for example: to disable dev mode in the staging build type (if configured)
 *   devDisabledInStaging: true,
 *   // The configuration property can be in the following formats
 *   //         'devDisabledIn${productFlavor}${buildType}'
 *   //         'devDisabledIn${buildType}'
 *
 *   // the root of your project, i.e. where "package.json" lives
 *   root: "../../",
 *
 *   // where to put the JS bundle asset in debug mode
 *   jsBundleDirDebug: "$buildDir/intermediates/assets/debug",
 *
 *   // where to put the JS bundle asset in release mode
 *   jsBundleDirRelease: "$buildDir/intermediates/assets/release",
 *
 *   // where to put drawable resources / React Native assets, e.g. the ones you use via
 *   // require('./image.png')), in debug mode
 *   resourcesDirDebug: "$buildDir/intermediates/res/merged/debug",
 *
 *   // where to put drawable resources / React Native assets, e.g. the ones you use via
 *   // require('./image.png')), in release mode
 *   resourcesDirRelease: "$buildDir/intermediates/res/merged/release",
 *
 *   // by default the gradle tasks are skipped if none of the JS files or assets change; this means
 *   // that we don't look at files in android/ or ios/ to determine whether the tasks are up to
 *   // date; if you have any other folders that you want to ignore for performance reasons (gradle
 *   // indexes the entire tree), add them here. Alternatively, if you have JS files in android/
 *   // for example, you might want to remove it from here.
 *   inputExcludes: ["android/**", "ios/**"],
 *
 *   // override which node gets called and with what additional arguments
 *   nodeExecutableAndArgs: ["node"],
 *
 *   // supply additional arguments to the packager
 *   extraPackagerArgs: []
 * ]
 */

project.ext.react = [
    entryFile: "index.js",
    enableHermes: false,  // clean and rebuild if changing
]

apply from: "../../node_modules/react-native/react.gradle"

/**
import of vector icons
*/
project.ext.vectoricons = [
    iconFontNames: [ 'Ionicons.ttf'] // Name of the font files you want to copy
]
apply from: "../../node_modules/react-native-vector-icons/fonts.gradle"

/**
 * Set this to true to create two separate APKs instead of one:
 *   - An APK that only works on ARM devices
 *   - An APK that only works on x86 devices
 * The advantage is the size of the APK is reduced by about 4MB.
 * Upload all the APKs to the Play Store and people will download
 * the correct one based on the CPU architecture of their device.
 */
def enableSeparateBuildPerCPUArchitecture = false

/**
 * Run Proguard to shrink the Java bytecode in release builds.
 */
def enableProguardInReleaseBuilds = false

/**
 * The preferred build flavor of JavaScriptCore.
 *
 * For example, to use the international variant, you can use:
 * `def jscFlavor = 'org.webkit:android-jsc-intl:+'`
 *
 * The international variant includes ICU i18n library and necessary data
 * allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that
 * give correct results when using with locales other than en-US.  Note that
 * this variant is about 6MiB larger per architecture than default.
 */
def jscFlavor = 'org.webkit:android-jsc:+'

/**
 * Whether to enable the Hermes VM.
 *
 * This should be set on project.ext.react and mirrored here.  If it is not set
 * on project.ext.react, JavaScript will not be compiled to Hermes Bytecode
 * and the benefits of using Hermes will therefore be sharply reduced.
 */
def enableHermes = project.ext.react.get("enableHermes", false);

android {
    compileSdkVersion rootProject.ext.compileSdkVersion

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    defaultConfig {
        applicationId "com.appName"
        minSdkVersion rootProject.ext.minSdkVersion
        targetSdkVersion rootProject.ext.targetSdkVersion
        versionCode 1 //not pretty but functional
        versionName "1.0" //not pretty but functional
    }
    splits {
        abi {
            reset()
            enable enableSeparateBuildPerCPUArchitecture
            universalApk false  // If true, also generate a universal APK
            include "armeabi-v7a", "x86", "arm64-v8a", "x86_64"
        }
    }
    signingConfigs {
        debug {
            storeFile file('debug.keystore')
            storePassword 'android'
            keyAlias 'androiddebugkey'
            keyPassword 'android'
        }
    }
    buildTypes {
        debug {
            signingConfig signingConfigs.debug
        }
        release {
            // Caution! In production, you need to generate your own keystore file.
            // see https://facebook.github.io/react-native/docs/signed-apk-android.
            signingConfig signingConfigs.debug
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
        }
    }
    // applicationVariants are e.g. debug, release
    applicationVariants.all { variant ->
        variant.outputs.each { output ->
            // For each separate APK per architecture, set a unique version code as described here:
            // https://developer.android.com/studio/build/configure-apk-splits.html
            def versionCodes = ["armeabi-v7a": 1, "x86": 2, "arm64-v8a": 3, "x86_64": 4]
            def abi = output.getFilter(OutputFile.ABI)
            if (abi != null) {  // null for the universal-debug, universal-release variants
                output.versionCodeOverride =
                        versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
            }

        }
    }
}

dependencies {
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation "com.facebook.react:react-native:+"  // From node_modules
    implementation 'androidx.appcompat:appcompat:1.1.0-rc01'
    implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.1.0-alpha02'

    if (enableHermes) {
        def hermesPath = "../../node_modules/hermes-engine/android/";
        debugImplementation files(hermesPath + "hermes-debug.aar")
        releaseImplementation files(hermesPath + "hermes-release.aar")
    } else {
        implementation jscFlavor
    }
}

// Run this once to be able to run the application with BUCK
// puts all compile dependencies into folder libs for BUCK to use
task copyDownloadableDepsToLibs(type: Copy) {
    from configurations.compile
    into 'libs'
}

apply from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project)
apply plugin: 'com.google.gms.google-services'

android/settings.gradle:

rootProject.name = 'AppName'
apply from: file("../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesSettingsGradle(settings)
include ':app'

MainApplication.java:

package com.appname;

import android.app.Application;
import android.content.Context;
import com.facebook.react.PackageList;
import com.facebook.react.ReactApplication;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.soloader.SoLoader;
import java.lang.reflect.InvocationTargetException;
import java.util.List;

public class MainApplication extends Application implements ReactApplication {

  private final ReactNativeHost mReactNativeHost =
      new ReactNativeHost(this) {
        @Override
        public boolean getUseDeveloperSupport() {
          return BuildConfig.DEBUG;
        }

        @Override
        protected List<ReactPackage> getPackages() {
          @SuppressWarnings("UnnecessaryLocalVariable")
          List<ReactPackage> packages = new PackageList(this).getPackages();
          // Packages that cannot be autolinked yet can be added manually here, for example:
          // packages.add(new MyReactNativePackage());
          return packages;
        }

        @Override
        protected String getJSMainModuleName() {
          return "index";
        }
      };

  @Override
  public ReactNativeHost getReactNativeHost() {
    return mReactNativeHost;
  }

  @Override
  public void onCreate() {
    super.onCreate();
    SoLoader.init(this, /* native exopackage */ false);
    initializeFlipper(this); // Remove this line if you don't want Flipper enabled
  }

  /**
   * Loads Flipper in React Native templates.
   *
   * @param context
   */
  private static void initializeFlipper(Context context) {
    if (BuildConfig.DEBUG) {
      try {
        /*
         We use reflection here to pick up the class that initializes Flipper,
        since Flipper library is not available in release mode
        */
        Class<?> aClass = Class.forName("com.facebook.flipper.ReactNativeFlipper");
        aClass.getMethod("initializeFlipper", Context.class).invoke(null, context);
      } catch (ClassNotFoundException e) {
        e.printStackTrace();
      } catch (NoSuchMethodException e) {
        e.printStackTrace();
      } catch (IllegalAccessException e) {
        e.printStackTrace();
      } catch (InvocationTargetException e) {
        e.printStackTrace();
      }
    }
  }
}

AndroidManifest.xml:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.appname">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_CALENDAR" />
    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <uses-permission android:name="android.permission.VIBRATE" />

    <application
      android:name=".MainApplication"
      android:label="@string/app_name"
      android:icon="@mipmap/ic_launcher"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:allowBackup="false"
      android:theme="@style/AppTheme">
      <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
        android:windowSoftInputMode="adjustResize"
        android:exported="true"
        android:launchMode="singleTop">
      </activity>
      <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
        <!-- add the following lines -->
        <activity
            android:name="com.zoontek.rnbootsplash.RNBootSplashActivity"
            android:theme="@style/BootTheme"> <!-- apply the theme you created at step 3. -->
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
        </activity>

        <!-- Maps SDK Key -->
        <meta-data
                android:name="com.google.android.geo.API_KEY"
                android:value="AIzaSyBPRDR3ZTriWwc5oF5NYqE7wG9qa5YBGjM"/>

      <!-- Set custom default icon. This is used when no icon is set for incoming notification messages.
       See README(https://goo.gl/l4GJaQ) for more. -->
      <meta-data
            android:name="com.google.firebase.messaging.default_notification_icon"
            android:resource="@drawable/ic_stat_noticon" />
      <!-- Set color used with incoming notification messages. This is used when no color is set for the incoming
         notification message. See README(https://goo.gl/6BKBk7) for more. -->
      <meta-data
            android:name="com.google.firebase.messaging.default_notification_color"
            android:resource="@color/primary" />

    </application>

</manifest>


Environment

Click To Expand

react-native info output:

System:
    OS: macOS Mojave 10.14.6
    CPU: (4) x64 Intel(R) Core(TM) i5-7267U CPU @ 3.10GHz
    Memory: 45.14 MB / 16.00 GB
    Shell: 3.2.57 - /bin/bash
  Binaries:
    Node: 8.11.3 - ~/.nvm/versions/node/v8.11.3/bin/node
    Yarn: 1.12.3 - ~/.nvm/versions/node/v8.11.3/bin/yarn
    npm: 6.10.2 - ~/.nvm/versions/node/v8.11.3/bin/npm
    Watchman: 4.9.0 - /usr/local/bin/watchman
  SDKs:
    iOS SDK:
      Platforms: iOS 13.2, DriverKit 19.0, macOS 10.15, tvOS 13.2, watchOS 6.1
  IDEs:
    Xcode: 11.3/11C29 - /usr/bin/xcodebuild
  npmGlobalPackages:
    react-native-macos-cli: 2.0.1
  • 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:
    • 6.2.0
  • Firebase module(s) you're using that has the issue:
    • @react-native-firebase/messaging
    • @react-native-firebase/app
  • Are you using TypeScript?
    • Y & 3.7.3


@KTDevelopment KTDevelopment changed the title (:fire:) onMessage is Not Called when App is Opened by clicking the notification 🔥onMessage is Not Called when App is Opened by clicking the notification Dec 22, 2019
@mikehardy
Copy link
Collaborator

There are many similar issues open right now. A few contain workarounds. What have you tried?

@KTDevelopment
Copy link
Author

What do you mean by workaround?
Should the onMessage function or better to say the callback passed to that function be called once the app is opened by a click on the notification?

Or is this kind of feature not possible with v6 of react-native-firebase?

@mikehardy
Copy link
Collaborator

Oh! sorry about that. I was crossing messaging and notifications in my mind. RNFBv6 does not do notifications.

@KTDevelopment
Copy link
Author

Ok, just to make it clear.
With RNFBv6 i can:

  • integrate FCM to be able to receive cloud Messages in my App in foreground.
  • when my app is not open, this cloudMessage is displayed as a "notification" (or is this the wrong name for messages at the dock)

but i can't:

  • get the cloud message when my app is opened by clicking the "notification" of the dock?

@mikehardy
Copy link
Collaborator

Basically yes but I'll draw a finer line with regard to payload. RNFBv6, use data-only messages, no notification payload. Use RNFB to catch the messages. Integrate with react-native-push-notifications to access local device APIs to do the notification bit

@KTDevelopment
Copy link
Author

Ok,
this seems a bit complicated for me, because it's more complicated to receive messages silent (different handling on both ios, android and not supported on ios by RNFBv6, as i know) and then using another framework to display a local notification to the user then just using notification messages right away.

Is there a reason why RNFBv6 is not getting the information about the notification which opens the App?
Or why RNFBv6 is using data-only messages only?

@mikehardy
Copy link
Collaborator

RNFBv6 does not do anything local notification related. Local notification APIs are actually unrelated to firebase APIs - messaging is a firebase service but notifications aren't an in practice for this library it was unsustainable to attempt to cover the APIs. If you think if's more complicated to use multiple frameworks you can imagine the complication of actually attempting to author one of the frameworks. You can read all about it in the pinned issue on this repo.

I was under the impression data only worked in all cases, it was just difficult to set up.

@KTDevelopment
Copy link
Author

Ok i will try to combine
RNFBv6 with https://github.com/zo0r/react-native-push-notification
and post my conclusions here, then i close the issue if i can get it to work

@KTDevelopment
Copy link
Author

KTDevelopment commented Dec 24, 2019

Hey,
after investigating hours of work i finally found a "solution". Sadly it's not perfekt but it's working for the moment.

Preamble

This is not a complete guide for installing RNFBv6 Messaging and RNPN (https://github.com/zo0r/react-native-push-notification), it just covers my problems after trying to use RNFBv6 Messaging. In the following RNFBv6 Messaging is just called RNFBv6.

Wording

PushNotifications -- remote Message from FCM with title, message and customData

Aim

First things first. What am I trying to achieve?
My server is sending PushNotifications with custom data attached. My app should display the notification to the user if the app is in background ore closed. After clicking the notification, my app should be visible and based on the notification the app should handle an action. If the app is opened, no notification should be displayed, instead the app should present an alert.

RNFBv6

At first installing RNFBv6 worked quite well and receiving Token worked. Handling PushNotifications was not really working. Now my way with RNPN:

Android

update android/app/src/main/AndroidManifest.xml

  1. add
android:launchMode="singleTop"

to the MainActivity entry

  1. add
<!-- Set custom default icon. This is used when no icon is set for incoming notification messages.
       See README(https://goo.gl/l4GJaQ) for more. -->
      <meta-data
            android:name="com.google.firebase.messaging.default_notification_icon"
            android:resource="@drawable/ic_stat_noticon" />
<!-- Set color used with incoming notification messages. This is used when no color is set for the incoming
         notification message. See README(https://goo.gl/6BKBk7) for more. -->
      <meta-data
            android:name="com.google.firebase.messaging.default_notification_color"
            android:resource="@color/primary" />

after the activities for configuring the native Notifications.
Make sure that the icon @drawable/ic_stat_noticon is present under android/app/src/main/res/drawable.

Now the PushNotification is received by onMessage of RNFBv6 when the app is opened
When the App is closed or in background the PushNotification is displayed to the user.
Clicking the PushNotification opens the app, but onMessage of RNFBv6 is not called.

  1. add RNPN,
    as i only want to use local handling yarn add react-native-push-notification did the job as google-play-services and firebase-messaging gradle packages are already installed

Now clicking the PushNotification opens the app and the onNotification from RNPN is called.
So Android is working correctly.

iOS

  1. add Capabilities with XCode Push Notifications and Background Modes - Remote Notification

  2. add
    #import <RNCPushNotificationIOS.h>
    and

// Required for the notification event. You must call the completion handler after handling the remote notification.
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
  [RNCPushNotificationIOS didReceiveRemoteNotification:userInfo fetchCompletionHandler:completionHandler];
}

// Required for the localNotification event.
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
  [RNCPushNotificationIOS didReceiveLocalNotification:notification];
}

Now all PushNotifications are received by onNotification of RNPN (as described in Aim).

getToken() problem

getToken() is working on Android with no problems. On iOS only the first call when "initializing" the notification handling works. All further calls are ending in Cloud Messaging "[messaging/unknown] The operation couldn’t be completed" (#2657) i hope this will be fixed by merging #3017 (hopefully). As for now, i just wrap it in a try catch and i hope the onTokenRefresh() works in the case the token is refreshed.

getInitialNotification() problem

getInitialNotification() of https://github.com/react-native-community/react-native-push-notification-ios used by RNPN only works on release builds of iOS seen here: react-native-push-notification/ios#24
So onNotification is only called on release builds.

Conclusion

For my 'simple' use case i have to do quite much work. Especially because documentations or installation guides are outdated very often. I hope this entry can help other people having problems at the moment, as it will maybe be outdated in the future, with upgrading from RNFBv5 to RNFBv6.
As a Suggestion for RNFBv6 i think it should handle receiving of Remote-PushNotifications in all 3 possible ways foreground, background and app closed. As default displaying wich is quite powerful, works out of the box for both Android and iOS as i could experience it. To access title and message of the PushNotification in onMessage or onNotification i maybe have to add it to the custom data but i think this is ok.
The messages received in onMessage and onNotification are in a different format, but as RNPN is displaying Notifications in the tray, even when the App is in foreground i have to deal with it at the moment.

@mikehardy maybe you can use something in the documentation of RNFBv6 Messaging or link this somewhere as known issues ore something like that. would have been really helpful for me. I don't have enough overview about threads and stuff.

@mikehardy
Copy link
Collaborator

Great write-up @KTDevelopment! - messaging and notifications are indeed quite difficult to get working right now and they are also one of the most important things everyone wants. We'll continue working to make them simply work (like the issues you mentioned) but for documentation I must admit the community is almost the best source of updates since people come to the project with fresh eyes. If there is anything you think is missing every documentation page has an edit button on the top right and github has a really streamlined/easy pull-request flow for documentation pull requests

@yash-atreya
Copy link

@KTDevelopment Thank you for this write-up! I was trying to implement this for a long time. But now I'm going to follow your write up and try it again.
Can I approach in this issue you if I have trouble setting it up??

@jordividaller
Copy link

Hi, Thx @KTDevelopment for your post. I tried this and everything working excepted that the OnNotification function is not called when App is in foreground, it works only when app is in background, and I don't understand why. Is it working for you ?

@jordividaller
Copy link

I find a solution if someone want to know, I use popInitialNotification from react-native-push-notification and it works with Foreground and background. Thx for this topic it really help me.

@stale
Copy link

stale bot commented Feb 6, 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 Feb 6, 2020
@idlework
Copy link

Same problem here, onMessage is not triggered when the app is in the background. @KTDevelopment solution works, but it should just work with FCM. If you send test message from the firebase FCM console, those should always trigger the onMessage handler, but this is not the case. Tested on 6.3.2

@stale stale bot removed the Type: Stale Issue has become stale - automatically added by Stale bot label Feb 13, 2020
@tmaly1980
Copy link
Contributor

tmaly1980 commented Feb 18, 2020

Guys, I'm a total newbie and most of this is way over my head. How am I supposed to integrate FCM with react-native-push-notification? I've followed the instructions for both - PushNotificationIOS is placed in AppDelegate.m, but what about all the react-native code? How do I get a FCM token? Does that have anything to do with the device token for APNS (triggered by PushNotification.configure)? I'd love to see a fully working example in javascript. I was using react-native-permissions to get around the getToken bug, but now that I've installed RNPN, it's back again. I'm just lost. At this point I'm probably going to go back to 5.x, but would really appreciate clear documentation on how to integrate.

@mikehardy You say there are certain types of messages that RNFB v6 will still receive? onMessage never fires when push notifications are sent to the device. When the app is in the background, it shows on the screen, but tapping onto the notification triggers no code once in the app, nor does anything happen if the app is in the foreground. I'm absolutely clueless on how to get RNFB onMessage to work. The Invertase documentation suggests it should work pretty easily. I'm unfortunately a (frustrated) newbie, so most of what I've spent several hours reading through on github/stackoverflow isn't helpful.

I should also clarify that I'm trying to send messages from the FCM dashboard. Something on the old RNFB site suggests that the console can only send notifications, which is handled by a separate notification library and that the data-only notifications that onMessage receives only data-only messages, which cannot be sent by the firebase console anyway, only through cloud functions/etc. So this adds confusion to the mix.

@Ehesp
Copy link
Member

Ehesp commented Mar 16, 2020

@tmaly1980 it is all pretty confusing to be honest. People using messaging/notifications in the same context don't help, especially when they're totally separate things :)

The below linked PR should help sort handling notifications from the console... I'll link it when it's live.

@Salakar Salakar added plugin: messaging FCM only - ( messaging() ) - do not use for Notifications Version: >= 6 labels Mar 27, 2020
@Salakar
Copy link
Member

Salakar commented Mar 27, 2020

This has been fixed in #3339 please try out the RC - 6.4.0-rc4.

@Salakar Salakar closed this as completed Mar 27, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
plugin: messaging FCM only - ( messaging() ) - do not use for Notifications
Projects
None yet
Development

No branches or pull requests

8 participants