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

firebase.notifications().getInitialNotification().then((notificationOpen: NotificationOpen) => Not working Always return Null in App.js #2768

Closed lovekothari123 closed 5 years ago

lovekothari123 commented 5 years ago

Issue

Describe your issue here Hello team, I am facing an issues with background notification as per your document. I am using this function For example :- **_

firebase
          .notifications()
          .getInitialNotification()
          .then((notificationOpen: NotificationOpen) => {
            console.log("getInitialNotification enter ");
            console.log(notificationOpen);
            if (notificationOpen) {
              // App was opened by a notification
              // Get the action triggered by the notification being opened
              const action = notificationOpen.action;
              // Get information about the notification that was opened
              const notification: Notification = notificationOpen.notification;

              console.log(notification);
            }
          });

So, when my application is in background or killed state and meanwhile i am click on notification. getInitialNotification() always return NULL.

package.json{
"react-native-firebase": "^5.5.6",
}

Note :- I am able to received notification in foreground/background state but in background state not able to read notification data/payload.

Testing payload type 👍

{"to":"dyr0r0fqBGA:APA91bHjxjOWZdqCCpyTAxFLTUZrWUvCiO3M3W4YD76eAK0OWbqd-DgWMfEQ6h59n0aP85KlfWIUSTe9Luk15KRXM8-Y7QOWjeGcnVsU9_lRTglN-L_75t6Kb8qBDnIws2IYuL0HhhFU",
"notification" : {
      "body": "Message Body",
      "title" : "Call Status",
      "sound": "default",
      "badge":"5"
   },
  "data": {
      "type": 1,
      "body": "Message Body",
      "title" : "Call Status"
  },
"priority":"high"}

_**


Project Files

iOS

Click To Expand

#### `ios/Podfile`: - [ ] I'm not using Pods - [x] I'm using Pods and my Podfile looks like: ```ruby ``` Here is my pod file data this content is only for firebase library. # Required by RNFirebase # Firebase pod 'Firebase', '~> 5.20.0' pod 'Firebase/Core', '~> 5.20.0' pod 'Firebase/Analytics', '~> 5.20.0' pod 'Firebase/DynamicLinks', '~> 5.20.0' pod 'Firebase/Messaging', '~> 5.20.0' pod 'React', path: rn_path, subspecs: [ 'Core', 'CxxBridge', 'DevSupport', 'RCTActionSheet', 'RCTAnimation', 'RCTGeolocation', 'RCTImage', 'RCTLinkingIOS', 'RCTNetwork', 'RCTSettings', 'RCTText', 'RCTVibration', 'RCTWebSocket', ] # React-Native libraries pod 'yoga', path: "#{rn_path}/ReactCommon/yoga" pod 'RNFirebase', :path => '../node_modules/react-native-firebase/iOS' pod "yoga", :path => "../node_modules/react-native/ReactCommon/yoga" #pod 'React', :path => '../node_modules/react-native/' pod 'Folly', :podspec => "#{rn_path}/third-party-podspecs/Folly.podspec" post_install do |installer| rnfirebase = installer.pods_project.targets.find { |target| target.name == 'RNFirebase' } ``` ``` ``` #import "AppDelegate.h" //Add this For Firebase only #import "Firebase.h" //Add this for notifications only #import "RNFirebaseNotifications.h" #import "RNFirebaseMessaging.h" @implementation AppDelegate //ADD Linking Code here ........... - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation { return [RCTLinkingManager application:application openURL:url sourceApplication:sourceApplication annotation:annotation]; // if (![RNBranch.branch application:app openURL:url options:options]) { // do other deep link routing for the Facebook SDK, Pinterest SDK, etc // } // return YES; } // 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]; return [RCTLinkingManager application:application continueUserActivity:userActivity restorationHandler:restorationHandler]; } //,.......tilll end here! - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { [Fabric with:@[[Crashlytics class]]]; [NSThread sleepForTimeInterval:1.0f]; // [RNBranch initSessionWithLaunchOptions:launchOptions isReferrable:YES]; // <-- add this //Add this lines For Notifications //For genrating tokens-----------------> [FIRApp configure]; //For in-app popup................... //Testiong .... [RNFirebaseNotifications configure]; [FIRMessaging messaging].delegate = self; //iOS 10 Notification installation ...... [[UNUserNotificationCenter currentNotificationCenter] setDelegate:self]; //iOS 10 Notification installation end ..... if ([UNUserNotificationCenter class] != nil) { // iOS 10 or later // For iOS 10 display notification (sent via APNS) [UNUserNotificationCenter currentNotificationCenter].delegate = self; UNAuthorizationOptions authOptions = UNAuthorizationOptionAlert | UNAuthorizationOptionSound | UNAuthorizationOptionBadge; [[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:authOptions completionHandler:^(BOOL granted, NSError * _Nullable error) { // ... }]; } else { // iOS 10 notifications aren't available; fall back to iOS 8-9 notifications. UIUserNotificationType allNotificationTypes = (UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge); UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:allNotificationTypes categories:nil]; [application registerUserNotificationSettings:settings]; } [application registerForRemoteNotifications]; [[FIRInstanceID instanceID] instanceIDWithHandler:^(FIRInstanceIDResult * _Nullable result, NSError * _Nullable error) { if (error != nil) { NSLog(@"Error fetching remote instance ID: %@", error); } else { NSLog(@"Remote instance ID token: %@", result.token); NSString* message = [NSString stringWithFormat:@"Remote InstanceID token: %@", result.token]; // self.instanceIDTokenMessage.text = message; } }]; //Add this for showing push pop-up on app.......................................? NSURL *jsCodeLocation; #ifdef DEBUG // Development jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil]; #else // Production jsCodeLocation = [[NSBundle mainBundle] URLForResource: @"main" withExtension: @"jsbundle"]; #endif NSDictionary *props = @{@"isDebugMode": @(NO), @"isTestMode": @(NO), @"isProdMode": @(YES)}; RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation initialProperties:props launchOptions:launchOptions]; rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f green:1.0f blue:1.0f alpha:1]; rootView.backgroundColor = [UIColor blackColor]; self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds]; self.window.backgroundColor = [UIColor blackColor]; UIViewController *rootViewController = [UIViewController new]; rootViewController.view = rootView; self.window.rootViewController = rootViewController; [self.window makeKeyAndVisible]; return YES; } - (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window { return [Orientation getOrientation]; } //Add other for background notifications .......................... - (void)messaging:(FIRMessaging *)messaging didReceiveRegistrationToken:(NSString *)fcmToken { NSLog(@"FCM registration token: %@", fcmToken); // Notify about received token. NSDictionary *dataDict = [NSDictionary dictionaryWithObject:fcmToken forKey:@"token"]; [[NSNotificationCenter defaultCenter] postNotificationName: @"FCMToken" object:nil userInfo:dataDict]; // TODO: If necessary send token to application server. // Note: This callback is fired at each app startup and whenever a new token is generated. } - (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]; //Read payload //Read payload .... } - (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings { [[RNFirebaseMessaging instance] didRegisterUserNotificationSettings:notificationSettings]; } // Add this for background popup @end ``` ```objc // For AppDelegate.h `@interface AppDelegate : UIResponder ` ```


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 //For Android ``` > buildscript { > repositories { > google() > jcenter() > maven { > url 'https://maven.google.com/' > name 'Google' > } > maven { url 'https://maven.fabric.io/public' } > } > dependencies { > classpath 'com.android.tools.build:gradle:3.5.0' > classpath 'io.fabric.tools:gradle:1.27.1' > classpath 'com.google.gms:google-services:4.3.2' > > // NOTE: Do not place your application dependencies here; they belong > // in the individual module build.gradle files > } > } > > allprojects { > repositories { > mavenLocal() > > google() > jcenter() > maven { > // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm > url "$rootDir/../node_modules/react-native/android" > } > maven { > url 'https://maven.google.com/' > name 'Google' > } > } > } > > subprojects { > afterEvaluate { project -> > if (project.hasProperty("android")) { > android { > compileSdkVersion rootProject.ext.compileSdkVersion > buildToolsVersion rootProject.ext.buildToolsVersion > } > } > } > } > > ext { > buildToolsVersion = "28.0.3" > minSdkVersion = 16 > compileSdkVersion = 28 > targetSdkVersion = 28 > supportLibVersion = '1.0.0-beta01' > googleServiceVersion = "17.2.0" > } > ``` ``` #### `android/app/build.gradle`: ```groovy // Firebase data only > dependencies { > > implementation project(':react-native-firebase') > > implementation "com.google.android.gms:play-services-base:16.1.0" > implementation "com.google.firebase:firebase-core:16.0.9" > // implementation "com.google.firebase:firebase-database:16.0.6" > implementation 'com.google.firebase:firebase-messaging:19.0.0' > implementation "com.google.firebase:firebase-auth:17.0.0" > implementation "com.google.firebase:firebase-analytics:${rootProject.ext.googleServiceVersion}" > // implementation "com.google.firebase:firebase-storage:+" > apply plugin: 'com.google.gms.google-services' ``` #### `android/settings.gradle`: ```groovy ``` include ':react-native-firebase' project(':react-native-firebase').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-firebase/android') ``` ``` #### `MainApplication.java`: ```java ``` import io.invertase.firebase.RNFirebasePackage; import io.invertase.firebase.analytics.RNFirebaseAnalyticsPackage; import io.invertase.firebase.messaging.RNFirebaseMessagingPackage; new RNFirebasePackage(), new RNFirebaseMessagingPackage(), // <-- Add this line new RNFirebaseAnalyticsPackage(), // <-- Add this line new RNFirebaseNotificationsPackage() ``` ``` #### `AndroidManifest.xml`: ```xml``` ``` ```


Environment

Click To Expand

**`react-native info` output:** ``` OUTPUT GOES HERE ``` info React Native Environment Info: System: OS: macOS High Sierra 10.13.6 CPU: (4) x64 Intel(R) Core(TM) i5-4308U CPU @ 2.80GHz Memory: 17.79 MB / 8.00 GB Shell: 3.2.57 - /bin/bash Binaries: Node: 10.15.3 - /usr/local/bin/node npm: 6.4.1 - /usr/local/bin/npm SDKs: iOS SDK: Platforms: iOS 12.1, macOS 10.14, tvOS 12.1, watchOS 5.1 Android SDK: API Levels: 23, 25, 27, 28 Build Tools: 23.0.1, 28.0.3 System Images: android-28 | Google APIs Intel x86 Atom, android-28 | Google Play Intel x86 Atom IDEs: Android Studio: 3.5 AI-191.8026.42.35.5791312 Xcode: 10.1/10B61 - /usr/bin/xcodebuild npmPackages: react: 16.8.1 => 16.8.1 react-native: ^0.59.3 => 0.59.3 npmGlobalPackages: create-react-native-app: 2.0.2 react-native-cli: 2.0.1 react-native-git-upgrade: 0.2.7 ``` ``` - **Platform that you're experiencing the issue on**: - [x] iOS - [x] Android - [ ] **iOS** but have not tested behavior on Android - [ ] **Android** but have not tested behavior on iOS - [x] Both - **`react-native-firebase` version you're using that has this issue:** - > `"react-native-firebase": "^5.5.6",` - **`Firebase` module(s) you're using that has the issue:** - `e.g. Instance ID` - **Are you using `TypeScript`?** - NO i am using .JS file


Think react-native-firebase is great? Please consider supporting all of the project maintainers and contributors by donating via our Open Collective where all contributors can submit expenses. [Learn More]

mikehardy commented 5 years ago

You must follow the template or we close the issue

As a hunch maybe make sure this isn't affecting you if you are on android https://github.com/crazycodeboy/react-native-splash-screen/issues/289#issuecomment-502406454

lovekothari123 commented 5 years ago

Hello @mikehardy please check above code and comments i have mention all information which is related to firebase please review all information.

mikehardy commented 5 years ago

You have picked and chosen which data to show, I can't spend time troubleshooting that way. You did not address my comment about possible splash-screen interaction and only the whole AndroidManifest.xml would show it.

lovekothari123 commented 5 years ago

thank-you thank-you thank-you thank-you thank-you thank-you thank-you thank-you thank-you thank-you thank-you thank-you thank-you thank-you thank-you sooooo much to share me this link crazycodeboy/react-native-splash-screen#289 (comment) @mikehardy
you are great i have solved my issues thank-you again @mikehardy 👍 👍 👍

mikehardy commented 5 years ago

By my count you are at least the 12th person just from this repo that has had that issue. :sweat_smile: glad that worked.

minhnguyenwp commented 5 years ago

@mikehardy Sorry, i face this issue, but android works fine. IOS is problem. i can get action when app is background, but app killed ios just opens app not goes to deeplink. i have getInitialNotification() <- not work when app killed, onNotificationOpened() <- it's fine,

any idea, Gents!

ramonvermeulen commented 5 years ago

I'm facing this issue as well. getInitialNotification().then(res => ...); is always returning null for me on iOS. On android everything is working just fine, any solutions? Using react-native-firebase 5.5.6 with react-native 0.59.9.

Any updates?

arunanna commented 5 years ago

@ramonvermeulen I am also having the same issue, except that my react native version is 0.61.0

Juliocbr commented 4 years ago

Did anyone find a solution for this error? I planned to upgrade from version 3.3.1 to 5.5.6 but apparently I will not do so for now.

davidwlhlm commented 4 years ago

Hi, do you have remote debugging enabled? I had the same issue last week with react-native 0.60.5 and react-native-firebase 5.5.6, but I could resolve the issue after turning "Debug JS Remotely" off.

I came to the solution after encountering a similar behaviour with React Native's Linking module. Linking.getInitialURL() (detecting with which link the app was initially opened) always returns null, if remote debugging is on.

mikehardy commented 4 years ago

@davidwlhlm that seems like such a gotcha - could you propose a PR to the docs with a troubleshooting section or something? I can't imagine the time lost trying to find that, and you've already found it :-). All docs have an edit button top-right

minhnguyenwp commented 4 years ago

Debug JS Remotely

i knew this issue, but the problem is i reported on real device with ipa and app from appstore.

ghasemikasra39 commented 4 years ago

Dear @minhnguyenwp I am facing exactly the same issue as yours in V7. I created the corresponding issue here. In the meanwhile, have you found any solution to this?

RishavKumar-3796 commented 4 years ago

Push notification does not give call back if there are multiple notifications in the notification console and when one notification is already clicked then clicking on another notification from the notification tray after closing the app does not call any notification life cycle method.

Let's say there are 5-6 notifications in the console, we click on one of the notification which opens up the app and works as expected and calls the related methods. After that when we close the app and then click on another notification from the notification console then it does not call any notification method.

I am using "react-native": "0.61.4", and "@react-native-firebase/messaging": "^7.4.2",

CoconutSiloDev commented 3 years ago

I am not sure if it is still related but for those who are using 'react-native-splash-screen', if you can, do not use this package as it has a number of serious unobservable issues. If you still decide to use it and if you also get null for messaging().getInitialNotificatio().

Make sure your SplashActivity.java is similar to this. I found this after getting null for three hours

-------------------------SplashActivity.java --------------------------------------------------------------------

package com.nameOfYourPackage;

import android.content.Intent; import android.os.Bundle; import androidx.appcompat.app.AppCompatActivity;

public class SplashActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);

    Intent fcmIntent = this.getIntent();
    Bundle bundle = fcmIntent.getExtras();

    Intent intent = new Intent(this, MainActivity.class);
    intent.putExtras(fcmIntent);
    startActivity(intent);
    finish();
}

}

cretumarius commented 3 years ago

@CoconutSiloDev Thanks man, you're awesome. I've faced the exact same problem and your comment solved my issue.