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鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

[馃悰] Firebase messaging onNotificationOpenedApp and getInitialNotification are not triggered on iOS #7055

Closed
2 of 10 tasks
sash20m opened this issue Apr 19, 2023 · 4 comments
Labels
Help: Needs Triage Issue needs additional investigation/triaging. Impact: Bug New bug report

Comments

@sash20m
Copy link

sash20m commented Apr 19, 2023

Issue

I have integrated firebase cloud messaging into the app, I used their library and followed the official documentation: https://rnfirebase.io/messaging/usage, I read everything from top to bottom and did all the necessary configs.

My problem is that the messaging().onNotificationOpenedApp(callback) and messaging().getInitialNotification do not run no matter what I try. the onMessage and the setBackgroundMessageHandler work perfectly expect the first two. My initial problem whas that setBackgroundMessageHandler wouldn't run either, but was able to fix that by sending the notification directly from my back-end with the apns key, like this:

const message = {
      notification: {
        title: 'test',
        body: 'body',
      },
      data: {
        routeRedirect: 'Page',
      },
      apns: {
        payload: {
          aps: {
            sound: 'default',
            contentAvailable: true,
          },
        },
        headers: {
          'apns-priority': '5',
        },
      },
      token:
        'my fcm token is here',
    };
    try {
      const res = await firebaseAdmin.messaging().send(message);

      console.log(res);
    } catch (error) {
      console.log('error', error.message);
    }

and now it works well for that part. I get notifications on my notification panel in iOS and I see in my terminal that the setBackgroundMessageHandler is being called when the notification arrives, which is as expected.
Here's the mobile code:

// requests permissions
firebaseNotifications.requestUserPermission();
// prints my token to the console
firebaseNotifications.getFCMToken();

messaging().onMessage((remoteMessage) => {
  console.log('New FCM Message -> ', JSON.stringify(remoteMessage));
});

messaging().onNotificationOpenedApp(remoteMessage => {
  console.log('onNotificationOpenedApp', remoteMessage.data);
});

messaging().setBackgroundMessageHandler(remoteMessage => {
  console.log('setBackgroundMessageHandler', remoteMessage);
  return '';
});

messaging()
  .getInitialNotification()
  .then(remoteMessage => {
    console.log('getInitialNotification', remoteMessage);
  });

function HeadlessCheck({ isHeadless }) {
  console.log(isHeadless, ' is headless?');
  if (isHeadless) {
    // App has been launched in the background by iOS, ignore
    return null;
  }

  return <App />;
}

AppRegistry.registerComponent(appName, () => HeadlessCheck);

Note here: I tried putting the event listeners in the App in a useEffect but still doesn't work.

When I put the app in background and then go and click on the notification, the app opens up but the onNotificationOpenedApp does not run, and when I close the app completely and click on the notification, the getInitialNotification returns null.

There's one thing that might have something to do with this, and that is that isHeadless keeps returning true. So if my app is in quit state, I send a notification and can see that the app had a quick load in the terminal, which is expected. But then when I open the app, from notification or otherwise, the isHeadless is true, which is very weird because it should have been true only when the app has been opened in the background when the notification came, but somehow it remains true.

Here's the code that I added to AppDelegate.mm to get the isHeadless value (otherwise it would be undefined every time).

  NSDictionary *initProps = [self prepareInitialProps];
//  UIView *rootView = RCTAppSetupDefaultRootView(bridge, @"myapp", initProps);
  
  NSDictionary *appProperties = [RNFBMessagingModule addCustomPropsToUserProps:nil withLaunchOptions:launchOptions];
  NSMutableDictionary *initialProps = [initProps mutableCopy];
  [initialProps addEntriesFromDictionary:appProperties];

normally only the first 2 lines would exists, but I commented the seconds and added the code below it.

I don't know if the isHeadless bug might have something to do with the handlers.

The package.json has this versions of the lib:

    "@react-native-firebase/app": "^17.4.2",
    "@react-native-firebase/messaging": "^17.4.2"

Note that on android all the event handlers work just fine, only iOS has this problem.

I am happy to give any info you might need in order to solve this. I have explored all the corners of the internet for a potential solution but none found.


Project Files

Javascript

Click To Expand

package.json:

# N/A

firebase.json for react-native-firebase v6:

{
    "react-native": {
      "messaging_ios_foreground_presentation_options": ["badge", "sound", "list", "banner"],
      "messaging_android_headless_task_timeout": 120000
    }
}

iOS

Click To Expand

ios/Podfile:

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

platform :ios, '12.4'
install! 'cocoapods', :deterministic_uuids => false

production = ENV["PRODUCTION"] == "1"

target 's4fmobile' do
  config = use_native_modules!

  pod 'GoogleSignIn', '~> 6.2.2'
  pod 'Firebase', :modular_headers => true
  pod 'FirebaseCore', :modular_headers => true
  pod 'FirebaseCoreInternal', :modular_headers => true
  pod 'GoogleUtilities', :modular_headers => true
  # use_frameworks! :linkage => :static
  # $RNFirebaseAsStaticFramework = true

  # Flags change depending on the env values.
  flags = get_default_flags()

  use_react_native!(
    :path => config[:reactNativePath],
    # to enable hermes on iOS, change `false` to `true` and then install pods
    :production => production,
    :hermes_enabled => flags[:hermes_enabled],
    :fabric_enabled => flags[:fabric_enabled],
    :flipper_configuration => FlipperConfiguration.enabled,
    # An absolute path to your application root.
    :app_path => "#{Pod::Config.instance.installation_root}/.."
  )

  target 's4fmobileTests' do
    inherit! :complete
    # Pods for testing
  end

  post_install do |installer|
    react_native_post_install(installer)
    __apply_Xcode_12_5_M1_post_install_workaround(installer)
  end
end

AppDelegate.mm:

// N/A


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:

 OUTPUT GOES HERE
  • 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:
    • 17.4.2
  • Firebase module(s) you're using that has the issue:
    • Messaging
  • Are you using TypeScript?
    • Y


@sash20m sash20m added Help: Needs Triage Issue needs additional investigation/triaging. Impact: Bug New bug report labels Apr 19, 2023
@brunofrigeri-lc
Copy link

+1. I'm experiencing the same issue.

@sash20m
Copy link
Author

sash20m commented Apr 19, 2023

@brunofrigeri-lc do you have also notifee ?

@brunofrigeri-lc
Copy link

@sash20m noo, not using notifee.

@sash20m
Copy link
Author

sash20m commented Apr 19, 2023

I just found out. It's from Notifee... Such insanity.
https://notifee.app/react-native/docs/release-notes#700
They explain that in a new version release but not mention how to go around that for apps using both libraries :@
I got white hairs from this.
I downgraded to v6.0.0 and now it works.

And the headless bug was because when the notification arrives and it opens the app in background, it takes couple of seconds to load because it's on localhost and it needs to connect to metro. Previously I would click on notification right when it came, that's why the headless remained true when the app would open up.

I suggest you add the listeners in a useEffect and send the notifications from the back-end with the apns key, this way the functions should work.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Help: Needs Triage Issue needs additional investigation/triaging. Impact: Bug New bug report
Projects
None yet
Development

No branches or pull requests

2 participants