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.53k stars 2.18k forks source link

iOS Background Notification troubleshooting #3367

Closed aslanon closed 3 years ago

aslanon commented 4 years ago

Issue

Hello, notifications run while the app is on the foregound, but I didn't receive any messages when the app is in the background or killed.

There are a lot of documentation but I can't solve this problem. What am I doing wrong?


Project Files

Javascript

Click To Expand

#### `package.json`: ```json "dependencies": { "@react-native-community/push-notification-ios": "^1.1.0", "@react-native-firebase/app": "^6.4.0-rc4", "@react-native-firebase/messaging": "^6.4.0-rc4", "react": "16.9.0", "react-native": "0.61.5", "react-native-push-notification": "^3.1.9", } ```

iOS

Click To Expand

#### `ios/Podfile`: - [ ] I'm not using Pods - [x] I'm using Pods and my Podfile looks like: ```ruby platform :ios, '10.0' require_relative '../node_modules/@react-native-community/cli-platform-ios/native_modules' target 'Myapp' do # Pods for Myapp 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' pod 'react-native-orientation', :path => '../node_modules/react-native-orientation' target 'MyappTests' do inherit! :search_paths # Pods for testing end use_native_modules! end target 'Myapp-tvOS' do # Pods for Myapp-tvOS target 'Myapp-tvOSTests' do inherit! :search_paths # Pods for testing end end ``` #### `AppDelegate.m`: ```objc /** * 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 #import #import #import #import #import #import "Orientation.h" @implementation AppDelegate // Required to register for notifications - (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings { [RNCPushNotificationIOS didRegisterUserNotificationSettings:notificationSettings]; } // Required for the register event. - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken { [RNCPushNotificationIOS didRegisterForRemoteNotificationsWithDeviceToken:deviceToken]; } // 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 registrationError event. - (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error { [RNCPushNotificationIOS didFailToRegisterForRemoteNotificationsWithError:error]; } // Required for the localNotification event. - (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification { [RNCPushNotificationIOS didReceiveLocalNotification:notification]; } - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { RCTBridge *bridge = [[RCTBridge alloc] initWithDelegate:self launchOptions:launchOptions]; RCTRootView *rootView = [[RCTRootView alloc] initWithBridge:bridge moduleName:@"Myapp" 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]; [FIRApp configure]; UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter]; center.delegate = self; 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 ```


Environment

Click To Expand

**`react-native info` output:** ``` info Fetching system and libraries information... System: OS: macOS 10.15.1 CPU: (4) x64 Intel(R) Core(TM) i5-5257U CPU @ 2.70GHz Memory: 2.36 GB / 16.00 GB Shell: 5.7.1 - /bin/zsh Binaries: Node: 12.13.0 - /usr/local/bin/node Yarn: 1.19.1 - /usr/local/bin/yarn npm: 6.12.0 - /usr/local/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.1/11C504 - /usr/bin/xcodebuild npmPackages: react: 16.9.0 => 16.9.0 react-native: 0.61.5 => 0.61.5 npmGlobalPackages: react-native-cli: 2.0.1 ``` - **Platform that you're experiencing the issue on**: - [x ] 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:** - `none // because I removed when I use to 6.4.0-rc4` - **`Firebase` module(s) you're using that has the issue:** - `e.g. Instance ID` - **Are you using `TypeScript`?** - `N`


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]

Ehesp commented 4 years ago

Can you show some code please?

Salakar commented 4 years ago

Also are you testing on a real device, background/quit states only work on a real device and not on the simulator. @Ehesp do we actually mention this on the docs anywhere btw?

Ehesp commented 4 years ago

I think so, may need making more obvious...

aslanon commented 4 years ago

I am testing on a real device.

App.js

import React, {useEffect, useState} from 'react';
import {Alert} from 'react-native';

import messaging from '@react-native-firebase/messaging';
import firebase from '@react-native-firebase/app';
import PushNotification from 'react-native-push-notification';
import PushNotificationIOS from '@react-native-community/push-notification-ios';

const App = () => {
  useEffect(() => {
    registerAppWithFCM();
    requestPermission();

    messaging().onNotificationOpenedApp(remoteMessage => {
      console.log(
        'Notification caused app to open from background state:',
        remoteMessage.notification,
      );
      Alert.alert(
        'Notification caused app to open from background state:',
        JSON.stringify(remoteMessage),
      );
    });

    // Check whether an initial notification is available
    messaging()
      .getInitialNotification()
      .then(remoteMessage => {
        if (remoteMessage) {
          console.log(
            'Notification caused app to open from quit state:',
            remoteMessage.notification,
          );
          Alert.alert(
            'Notification caused app to open from quit state:',
            JSON.stringify(remoteMessage),
          );
        }
      });

    const unsubscribe = messaging().onMessage(async remoteMessage => {
      Alert.alert('A new FCM message arrived!', JSON.stringify(remoteMessage));

      PushNotification.localNotification({
        title: 'notification.title',
        message: 'notification.body!',
      });
    });

    return unsubscribe;
  }, []);

  async function registerAppWithFCM() {
    await messaging().registerDeviceForRemoteMessages();
  }

  async function requestPermission() {
    const granted = await messaging().requestPermission({
      alert: true,
      announcement: false,
      badge: true,
      carPlay: true,
      provisional: false,
      sound: true,
    });
    if (granted) {
      const fcmToken = await messaging().getToken();
      console.log(fcmToken);
      console.log('User granted messaging permissions!');
    } else {
      console.log('User declined messaging permissions :(');
    }
  }

  return (
   <View></View>
  );
};

export default App;

index.js

/**
 * @format
 */

import React from 'react';
import {AppRegistry, Alert} from 'react-native';
import App from './App';
import {name as appName} from './app.json';

import messaging from '@react-native-firebase/messaging';

messaging().setBackgroundMessageHandler(async remoteMessage => {
  console.log('Message handled in the background!', remoteMessage);
  Alert.alert('BACKGROUND', JSON.stringify(remoteMessage));
});

function HeadlessCheck({isHeadless}) {
  if (isHeadless) {
    // App has been launched in the background by iOS, ignore
    return null;
  }
  return <App />;
}

AppRegistry.registerComponent(appName, () => HeadlessCheck);
Ehesp commented 4 years ago

How are you checking whether the background events are working? You're doing an alert, however there's no app to trigger an alert in the background?

gmertk commented 4 years ago

Just passing by as I was looking through notification issues.

Correct me if I'm wrong but this looks sketchy:

    registerAppWithFCM();
    requestPermission();

According to docs, requestPermission must be called once the the app has registered with FCM. Since both of your functions are async, you might ask for permissions before registerAppWithFCM resolves.

Not sure if this would break anything. Maybe others shed some light on this.

ixuz commented 4 years ago

I experience similar issue after upgrading to this version 6.4.0-rc4, somehow my App successfully obtains an FCM token from the Firebase Messaging SDK, but the application itself is not visible in the iOS Notification settings page.

My hunch is that the Firebase Messaging SDK somehow fails to register the App for push notifications, but returns an fcm token anyway. ๐Ÿ˜•

ngregrichardson commented 4 years ago

I'm having the same issue. I receive notifications in the foreground, but the code from onMessage isn't called until the app is brought to the foreground again after receiving a notification in the background. I am on the same version numbers and am also on a real device. I am following this order:

  1. await registerDeviceForRemoteMessages
  2. hasPermission/requestPermission
  3. setup onTokenRefresh
  4. setBackgroundMessageHandler
Ehesp commented 4 years ago

@aslanon looking at your AppDelegate file, you've got loads of other methods which are calling RNCPushNotificationIOS. I suspect this will be causing some problems. Try to remove these and see if things work.

Also as @gmertk pointed out, your code is going to be subject to race conditions, and also you're not catching any errors.

@ixuz Is the request for permissions popup showing? No notifications option is nothing to do with whether remote ones can be received, that means the permissions request was never triggered.

ixuz commented 4 years ago

@aslanon looking at your AppDelegate file, you've got loads of other methods which are calling RNCPushNotificationIOS. I suspect this will be causing some problems. Try to remove these and see if things work.

Also as @gmertk pointed out, your code is going to be subject to race conditions, and also you're not catching any errors.

@ixuz Is the request for permissions popup showing? No notifications option is nothing to do with whether remote ones can be received, that means the permissions request was never triggered.

The permission request pop-up does not automatically show up, however I still get the fcm token in return.

await firebase.messaging().requestPermission({
      alert: true,
      announcement: false,
      badge: true,
      carPlay: false,
      provisional: false,
      sound: true
    }
Ehesp commented 4 years ago

Yeah they're not related. Permissions is a local device thing which iOS reads when it needs to display a notification (if it doesn't have permission, it won't show).

The FCM token is requested when you register the device.

ixuz commented 4 years ago

@Ehesp I've adjusted my code slightly, and found the reason why I did not receive any push notification permission request pop-up. I didn't evaluate the hasPermission against the AuthorizationStatus keys.

So now the request permission popup is showing up, and upon acceptance, the app shows up in the iOS Settings/Alarms screen(all permissions granted). All good! ๐Ÿ‘

Except for one thing, whenever I try to send a push notification to the obtained fcm token, it never shows up on the device.

Here's a complete sample of how I'm obtaining the fcm token.

if (!firebase.messaging().isDeviceRegisteredForRemoteMessages) {
  await firebase.messaging().registerDeviceForRemoteMessages();
}

let authStatus = await firebase.messaging().hasPermission();

if (authStatus !== firebase.messaging.AuthorizationStatus.AUTHORIZED) {
  authStatus = await firebase.messaging().requestPermission({
    alert: true,
    announcement: false,
    badge: true,
    carPlay: false,
    provisional: false,
    sound: true
  });
}

if (authStatus === firebase.messaging.AuthorizationStatus.AUTHORIZED) {
  const token = await firebase.messaging().getToken();
  if (token) {
    // Here the "token" is defined, but push notifications never arrive using this fcm token...
  }
}

I'm sending my test push notification via the Firebase project page "Compose notification">"Send test message".

Any advice?

Salakar commented 4 years ago
Details

@ixuz Can you confirm:

ixuz commented 4 years ago

@Salakar I confirm:

Salakar commented 4 years ago

@ixuz uninstall and re-install the app on your device once you've made that change. Note after doing this you will have a new token though

ixuz commented 4 years ago

@Salakar Alright, I've followed your advice, see my steps below:

  1. Completely uninstalled app from device.
  2. I've omitted the if condition
    //if (!firebase.messaging().isDeviceRegisteredForRemoteMessages) {
    await firebase.messaging().registerDeviceForRemoteMessages();
    //}
  3. Xcode Clean -> Build (Release version + signing) -> Run (on real device: Iphone 5c)
  4. App launches, prompt appears asks me to accept push notification. I click agree. (at this point I can see that a new token was obtained and sent to our api)
  5. Now I close our App on the device again(fully terminated app process). And I also verify that all permissions are granted in iOS settings/alarms/Our app. Confirm all sliders are active.
  6. I let the device go to lockscreen/sleep.
  7. Finally, I try send a test push notification via the Firebase project page "Compose notification">"Send test message" (of course using that newly obtained token).

No dice, the push notification does not appear on my device. ๐Ÿ˜–

Anything else I could be missing? Thank you so far!

aslanon commented 4 years ago

I used console.log and local UI notification for background notifications but I deleted these codes when copy to here. @Ehesp .

I tried different things, but my problem is not solved. While the application is foreground, notifications are coming from the remote server. I also send notifications through the Firebase Cloud Messaging interface. @gmertk

resim

onMessage response:

A new FCM message arrived! {"data":{"title":"BaลŸlฤฑk","notification":{"title":"BaลŸlฤฑk","e":"1","body":"mesaj"},"content_available":"true","body":"mesaj"},"collapseKey":"com.mobile.Hybrone","from":"1041079541037"}

@aslanon looking at your AppDelegate file, you've got loads of other methods which are calling RNCPushNotificationIOS. I suspect this will be causing some problems. Try to remove these and see if things work.

Also as @gmertk pointed out, your code is going to be subject to race conditions, and also you're not catching any errors.

The push-notification-ios library was running until I installed @react-native-firebase/app and @react-native-firebase/messaging. But now, it is not working. I removed this package after your comment.

Right now, I choose this option from the menu and the app goes to the background. Then I send the notification. But I can't see an output at the terminal. But when I get back to the application, the notification comes to the terminal.

resim

How do you suggest testing background notifications? @Ehesp

Thank you for your help. @Ehesp @Salakar @gmertk

Ehesp commented 4 years ago

Hmm, everything looks as it should be to be honest.

When writing the new version, we hit an issue on older iOS devices where an incoming message was being ignored because the device did not have enough resource to handle it. We only found this out by looking in the iOS logs.

@Salakar is there anyway to easily access those logs apart from digging into XCode?

thehappydinoa commented 4 years ago

@Ehesp We tried using @aslanon 's Simulate Background Fetch option and had notifications come through fine, but otherwise it is broken. Is there anything I can help debug or try?

Ehesp commented 4 years ago

Interesting... Let me look into what that is actually doing and I'll take a look. On the face of it, it'd seem a background fetch on the device is not happening. Can you show a screenshot of your XCode capabilities?

aslanon commented 4 years ago

Have you tried with the latest version of React Native (ios)? Can you share a example app project? @Ehesp

Screenshot 2020-03-31 at 13 07 43
embpdaniel commented 4 years ago

I'm also having similar issues as has been mentioned. I've tested building with my previous app version (same project, which used v5.2.2) vs 6.4.0-rc4. 5.2.2 works without issues.

aslanon commented 4 years ago

What is your react-native version working with v5.2.2? @embpdaniel

Ehesp commented 4 years ago

@embpdaniel What device are you trying it with (and what iOS version)? When we were testing, old devices were struggling to handle a background payload fetch due to a lack of system resource available.

embpdaniel commented 4 years ago

@aslanon The react native version for v5.2.2 is 0.57.8

@Ehesp I am testing on an iPhone X with ios version 13.3.1. The device is not old and pretty bare (I just use it to test apps) so it should be able to handle it.

embpdaniel commented 4 years ago

If it helps, my upgraded app uses version 0.61.5 of react native. The firebase dependencies I use for that version are:

    "@react-native-firebase/app": "6.4.0-rc4",
    "@react-native-firebase/crashlytics": "6.4.0-rc4",
    "@react-native-firebase/messaging": "6.4.0-rc4",
Ehesp commented 4 years ago

@embpdaniel Thanks - very strange one.

Would it be possible for you to try this script to send something to your device? We use this locally and everything is currently working:

const admin = require("firebase-admin");
const serviceAccount = require("./admin-credentials");

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: "todo"
});

const registrationToken = 'todo'; // fcm token

async function run() {
  await admin.messaging().sendToDevice(
    registrationToken,
    {
      // notification: {
      //   title: 'foo',
      //   body: 'bar',
      //   subtitle: 'bar',
      //   click_action: 'foo',
      //   badge: '3',
      //   sound: 'chime',
      // },
      data: {
        foo2: "testers",
        foo4: "barrrzr"
      }
    },
    {
      contentAvailable: true,
      apnsPushType: "background",
      priority: "high"
    }
  );
}

run().then(console.log).error(console.log);

You'll need the service account and the device FCM token. Comment in the notification payload too.

Be great if you could try that out for us. If that fails to work, is there any possibility of one of us screen-sharing?

embpdaniel commented 4 years ago

Hi @Ehesp this is to place on the server-side right? I don't have access to the server only to the front end, and the back end is PHP so I don't think we can run that anyway. However I can ask the backend developer if he'd like to hop on a video chat with us and see if we can look through it together. I'll check with him and will get back to you.

Salakar commented 4 years ago

Have spent the day testing this again; here's my findings:

iPhone 5s - iOS 12.4.5

Foreground

Foreground = App is visible & open

Notification+Data: โœ…

Notification not shown to user, only event received (correct behaviour) image

Notification only: โœ…

Notification not shown to user, only event received (correct behaviour) image

Data only: โœ…

image


Background

Background = App is not visible, but still running in background (can see it on App Switcher still)

Notification+Data: โœ…

Notification is shown to user and event received (correct behaviour). Event is only received if content-available is set, notification will display with or without content-available.

image

Notification only: โœ…

Notification is shown to user and event received (correct behaviour). Event is only received if content-available is set, notification will display with or without content-available.

image

Data only: โœ…

Event is received (correct behaviour). Event is only received if content-available is set.

image


App Closed / Swiped away

App Closed = App is not visible and has been dismissed from App Switcher (and no longer visible there either).

Notification+Data: ๐Ÿ”ถ

Notification is shown to user (correct) but event not received (incorrect if content-available is set).

Notification only: ๐Ÿ”ถ

Notification is shown to user (correct) but event not received (incorrect if content-available is set).

Data only: ๐Ÿ”ถ

Event is not received (incorrect). content-available is set

For these App Closed ones on iPhone 5s/iOS 12 - the system is receiving the messages but the system service responsible for launching the app in the background is refusing to launch the application (without a reason specified, it will normally give you a reason why it's refusing to launch, e.g. battery status or high CPU usage on the device):

image

Don't think there is anything we can do about this one - it does look like an iOS issue but good luck getting Apple to look at it ๐Ÿ˜…;



iPhone 7 - iOS 13.3.1

Foreground

Foreground = App is visible & open

Same behaviour as iPhone 5s above.


Background

Background = App is not visible, but still running in background (can see it on App Switcher still)

Same behaviour as iPhone 5s above.


App Closed / Swiped away

App Closed = App is not visible and has been dismissed from App Switcher (and no longer visible there either).

Notification+Data: โœ…

Notification is shown to user (correct). Event is received if content-available is set (correct). App is launched silently with isHeadless react prop.

image

Notification only: โœ…

Notification is shown to user (correct). Event is received if content-available is set (correct). App is launched silently with isHeadless react prop.

image

Data only: โœ…

Event is received if content-available is set (correct). App is launched silently with isHeadless react prop.

image

Salakar commented 4 years ago

So other than the apparent issue with my 5s device or iOS 12 when the app is fully quit - everything else seems to be functioning correctly

Salakar commented 4 years ago

It will help debug what peoples specific iOS issues are if you could also provide system logs for your devices;

  1. Open the Console app on your Mac
  2. Select your iPhone from the devices list on the left hand side
  3. Filter messages by typing in your Bundle ID into the search box and pressing enter.
  4. Press the clear button to clean the history.
  5. Now send the message to your device
  6. Select all the rows on the logs & copy them, Cmd + C (not available on right-click menu)
  7. Paste them here in a reply in a code block

image

The main processes of interest on the logs are SpringBoard & dasd

embpdaniel commented 4 years ago

@Ehesp We are available tomorrow for a screen-share 12-3:30 PM EST, or Friday 12PM-5PM EST.

Are you able to make it? Let me know, and thank you it's much appreciated.

bsonmez commented 4 years ago

Hey @Salakar. I also cannot receive notifications in real device iOS 13.4 iPhone 7 Plus. However, I also tried iPhone 6 with iOS 12, it worked. In a simulator, I can see the remote message delivered but it cannot be handled in the real device.

I try to search the app on the console. Here are the results.

Screen Shot 2020-04-02 at 07 28 27

What can I do next? Or what Informations should I provide more?

embpdaniel commented 4 years ago

Hey guys, just an update from my part. It's working now. I tested again today on my same exact setup:

React Native 0.61.5 React Native Firebase 6.4.0-rc4 iPhoneX 13.3.1

Nothing changed since my last test, and now I am receiving notifications. So I'm not sure what happened before but maybe it was a temporary server-side issue -- something outside of the react native setup.

Just to be clear, these are the events I register for which are working and when they fire for me:

messaging().onMessage

^This is called when my app is in the foreground and a notification comes in. It does not fire if my app is in the background or closed

messaging().onNotificationOpenedApp

^This is called when my app is in the background and I tap on the notification to open my app.

messaging().getInitialNotification()

^ This is called when my app is closed and I tap on a notification to open the app

I believe that covers all possible cases on iOS, but if you'd like me to test anything else I'd be happy to. Just let me know

ixuz commented 4 years ago

Same here, tested again today and it works again, without any significant changes. ๐Ÿ˜•

LuongTruong commented 4 years ago

Hello @ixuz , I have the same issue as you. The Push notification is implemented with:

After that, I use v6.

There is nothing change but iOS doesn't work. After do some testing, I found that the function

    messaging().registerDeviceForRemoteMessages()

Is not triggered

Salakar commented 4 years ago

@ixuz @embpdaniel - if its working for you now this most likely means your device was throttling the messages, there are some strict rules it has internally on iOS e.g. high CPU usage policy, battery low policy, phone just started policy (300-900secs after starting device there is heavy throttling), thundering herd policy (too many processes running on device recently) etc.

What I have noticed though is that even if it does not come through immediately it does seem to come through eventually when policies are all good or when the app next open (needs confirming).

Those logs I mentioned above will give you an indication of what's happened most of the time. But yep this is all iOS behaviour out of our control ๐Ÿ˜”

Ehesp commented 4 years ago

Once the release is out & the docs site goes live I'll add some troubleshooting docs.

LuongTruong commented 4 years ago

Hello @aslanon ,

The push-notification-ios library was running until I installed @react-native-firebase/app and @react-native-firebase/messaging. But now, it is not working. I removed this package after your comment.

I have the same problem. In my app, the push-notification-ios can send local notification perfectly, but when the package @react-native-firebase/messaging installed, no more local notification received.

If you have a solution for this, please let me know. Many thanks

embpdaniel commented 4 years ago

I may be experiencing the same as @LuongTruong . I am using push-notification-ios to send local notifications and have everything set up as required by that library, but it's not working as of right now.

thehappydinoa commented 4 years ago

Same here, I had to add some stuff to my App Delegate, but would love an answer

ASchwad commented 4 years ago

Im troubleshooting this aswell... I think my AppDelegate.m got messed up with the various Version and package changes. Could somebody please post a working AppDelegate.m Config for the current react-native-firebase version 6.4.0?

thehappydinoa commented 4 years ago

Here is my working full AppDelegate.m

I imported RNCPushNotificationIOS

#import <RNCPushNotificationIOS.h>

Added this inside didFinishLaunchingWithOptions

[[UIApplication sharedApplication] registerForRemoteNotifications];

Then added these functions under the didFinishLaunchingWithOptions function

// Required to register for notifications
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings
{
  [RNCPushNotificationIOS didRegisterUserNotificationSettings:notificationSettings];
}
// Required for the register event.
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
  [FIRMessaging messaging].APNSToken = deviceToken;
  [RNCPushNotificationIOS didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];
}
// Required for the registrationError event.
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
  [RNCPushNotificationIOS didFailToRegisterForRemoteNotificationsWithError:error];
}
LuongTruong commented 4 years ago

Hello @thehappydinoa , after changing my code like your suggestion, the remote push notification still works, but the local push notification still doesn't show up.

Can you or anyone give me more details? Many thanks, guys

LuongTruong commented 4 years ago

Hello guys, I found a new thing here. The version of /app and /messaging is downgrade to 6.3.4 and my local push notification works without changing anything.

Local push notification not working since version 6.4.0

Ehesp commented 4 years ago

This looks like an issue with the delegates not working when both are present. I believe @Salakar has an idea on how to sort so will be fixed asap.

Ehesp commented 4 years ago

Although 6.3.4 may seem to work, there's some underlying issues with how the device is registered and when the FCM token is attached. Also permissions are limited & there's no notification interaction - use at your own risk if you upgraded.

LuongTruong commented 4 years ago

Hello @Ehesp , after reading the release notes of version 6.4.0, there are many improvements and critical bug fix. Therefore, I am using 6.4.0 and the local notification I just use a fake popup.

This looks like an issue with the delegates not working when both are present. I believe @Salakar has an idea on how to sort so will be fixed asap.

I am so happy to know that you guys will come with the solution soon ^^

Last but not least, anyone who want to downgrade the version from 6.4.0 to 6.3.4, please read the release notes carefully

gmertk commented 4 years ago

Quick question; do I need to make any changes to AppDelegate if I'm only using @react-native-firebase/messaging for notifications? (no usage of @react-native-community/push-notification-ios or such) No mention of AppDelegate in the rnfirebase docs, but I've just wanted to make sure.

andreasanta commented 4 years ago

@gmertk As far as I know, as long as you set FirebaseAppDelegateProxyEnabled=YES in your Info.plist - or leave it unset - the native module delegates should be called transparently. So no need to alter your AppDelegate.m.

In case you set FirebaseAppDelegateProxyEnabled=NO, then you need to forward your calls to the corresponding React Native Firebase Messaging handlers.

If you start getting promises that never resolve, you should check this setting.