Shivangi Agrawal
Shivangi Agrawal

Reputation: 149

iOS background notification handler issue using @react-native-firebase/messaging

I am facing the issue when the app is in background or closed state. The notifications are shown in the notification center in all cases but the messaging().setBackgroundMessageHandler doesn't get called every time but only some times while checked rigorously on the app. Followed the official documentation for cloud messaging, upgraded to version 10.2.0 for @react-native-firebase/messaging and @react-native-firebase/app. All the states callbacks are working fine in Android and obtained perfectly every time, the issues exist only for iOS and not sure what is causing all this mess.

Adding here code for ref that I am using. In the entry file i.e. index.js

messaging().setBackgroundMessageHandler(async (remoteMessage) => {
  console.log("Message handled in the background! 1", remoteMessage);
});

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

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

In App.js:

const App = () => {
  var notif = new NotifService();
  useEffect(() => {
    requestUserPermission()
    checkPermission()
    console.log("checkPermission")

    const unsubscribe = messaging().onMessage(async remoteMessage => {
      console.log("A new FCM message arrived!: foreground: ", remoteMessage)
      console.log("A new FCM message arrived!: foreground: ", remoteMessage.messageId)
      // Alert.alert('A new FCM message arrived!: foreground: ', JSON.stringify(remoteMessage));
      notif.localNotif();
    });
  
    return unsubscribe;
  }, []);

  useEffect(() => {
    messaging().onNotificationOpenedApp(remoteMessage => {
      console.log(
        'Notification caused app to open from background state:',
        remoteMessage.notification,
      );
      Alert.alert('Message handled in the background state!', JSON.stringify(remoteMessage));
      // navigation.navigate(remoteMessage.data.type);
    });
  
    // 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('Message handled in the quit state!', JSON.stringify(remoteMessage));
          // setInitialRoute(remoteMessage.data.type); // e.g. "Settings"
        }
        // setLoading(false);
      });
  }, []);

  async function requestUserPermission() {
    const authStatus = await messaging().requestPermission();
    const enabled =
      authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
      authStatus === messaging.AuthorizationStatus.PROVISIONAL;
  
    if (enabled) {
      console.log('Authorization status:', authStatus);
    }
  }

    // 1
    async function checkPermission() {
      const enabled = await messaging().hasPermission();
      console.log("checkPermission: enabled: ", enabled)
      if (enabled) {
        getToken();
      } else {
        requestPermission();
      }
    }
  
    // 3
    async function getToken() {
      let fcmToken = await AsyncStorage.getItem('fcmToken');
      console.log('fcmToken @@1:', fcmToken);
      if (!fcmToken) {
        fcmToken = await messaging().getToken();
        console.log('fcmToken @@2:', fcmToken);
        if (fcmToken) {
          // user has a device token
          await AsyncStorage.setItem('fcmToken', fcmToken);
        }
      }
    }
  
    // 2
    async function requestPermission() {
      console.log("requestPermission:")
      try {
        await messaging().requestPermission();
        // User has authorised
        getToken();
      } catch (error) {
        // User has rejected permissions
        console.log('permission rejected');
      }
    }
}

Payload that I tested using firebase rest API:

{ "to": "TOKEN_HERE", "data": { "notification": { "title": "ABC1", "body": "xyz1" }, "Name": "121" }, "notification": { "title": "ABC1", "body": "xyz1" }, "priority": "high", "content_available": true }

Please add here if anybody faced same issue and resolved that. Stuck for days with this now! Thanks.

Upvotes: 4

Views: 3311

Answers (1)

o.o
o.o

Reputation: 108

Use new API onBackgroundMessage instead

Version 7.18.0 - August 13, 2020 Cloud Messaging
Deprecated setBackgroundMessageHandler. Use the new API onBackgroundMessage instead.

https://firebase.google.com/support/release-notes/js#cloud-messaging_2

Upvotes: -5

Related Questions