react-native-firebase icon indicating copy to clipboard operation
react-native-firebase copied to clipboard

iOS Background Notification troubleshooting

Open aslanon opened this issue 6 years ago • 214 comments

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:

  "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:
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:

/**
 * 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 <Firebase.h>
#import <RNCPushNotificationIOS.h>
#import <UserNotifications/UserNotifications.h>

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

aslanon avatar Mar 29 '20 19:03 aslanon

Can you show some code please?

Ehesp avatar Mar 29 '20 19:03 Ehesp

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?

Salakar avatar Mar 29 '20 19:03 Salakar

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

Ehesp avatar Mar 29 '20 19:03 Ehesp

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);


aslanon avatar Mar 29 '20 19:03 aslanon

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?

Ehesp avatar Mar 29 '20 20:03 Ehesp

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.

gmertk avatar Mar 29 '20 23:03 gmertk

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. 😕

ixuz avatar Mar 30 '20 03:03 ixuz

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

ngregrichardson avatar Mar 30 '20 04:03 ngregrichardson

@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.

Ehesp avatar Mar 30 '20 08:03 Ehesp

@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
    }

ixuz avatar Mar 30 '20 08:03 ixuz

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.

Ehesp avatar Mar 30 '20 08:03 Ehesp

@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?

ixuz avatar Mar 30 '20 09:03 ixuz

Details

@ixuz Can you confirm:

  • this is on a real device
  • PushNotifications capability added to your Xcode project
  • if data messages & for background/quit states;
    • Background Modes -> Remote Notifications is added to your Xcode project capabilities.
    • APNS content-available is set on message payload & priority is high

Salakar avatar Mar 30 '20 10:03 Salakar

@Salakar I confirm:

  • Real device "iPhone 5c", not a simulator.
  • Confirms PushNotifications capability is added to Xcode project, also our push notifications worked with the prior version: 6.3.4.
  • Confirms Background Modes -> Remove Notification is added and checked.

ixuz avatar Mar 30 '20 10:03 ixuz

@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

Salakar avatar Mar 30 '20 10:03 Salakar

@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();
//}
  1. Xcode Clean -> Build (Release version + signing) -> Run (on real device: Iphone 5c)
  2. 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)
  3. 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.
  4. I let the device go to lockscreen/sleep.
  5. 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!

ixuz avatar Mar 30 '20 10:03 ixuz

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

aslanon avatar Mar 30 '20 15:03 aslanon

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?

Ehesp avatar Mar 30 '20 15:03 Ehesp

@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?

thehappydinoa avatar Mar 30 '20 18:03 thehappydinoa

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?

Ehesp avatar Mar 31 '20 09:03 Ehesp