Implement Remote Push Notification Badges (IOS) on background React Native Apps
Andreas Beyer

Andreas Beyer @ndbeyer

About: Fullstack React/React Native Developer

Joined:
Feb 19, 2024

Implement Remote Push Notification Badges (IOS) on background React Native Apps

Publish Date: Jul 18 '24
0 0

For me it was somewhat annoying to find the simplest path to implement remote push notifications (PN) badges (ios) on background React Native apps.

I suppose you already have set up your PNs based on e.g. firebase.

We don't use the following approaches

  • the server controlled way setting apns.payload.aps.badge (It is annoying to handle that logic for each user in the backend)
  • the NotificationService.swift and UserDefaults approach (it is ok to write Swift, but it is still annoying to use XCode)

Ok let's go:

  • Make sure to request badge permissions, this took me quite a while to check that this is required, otherwise you'll receive PNs but no badge will ever appear anywhere - there won't even be the badge slider available in your app settings.
import { requestNotifications } from 'react-native-permissions'
...
React.useEffect(() => {
   requestNotifications(['alert', 'badge'])
},[])

Enter fullscreen mode Exit fullscreen mode
  • Create a CloseStatePseudoApp to make sure that firebaseMessagings background messages run even if the app is in closed state

const MainApp  = () => ...

const ClosedStatePseudoApp = () => {
    React.useEffect(() => {
        SplashScreen.hide();
    }, []);

    return null;
};

AppRegistry.registerComponent('YourAppname', (props) =>
    props?.isHeadless ? ClosedStatePseudoApp() : MainApp()
);
Enter fullscreen mode Exit fullscreen mode
  • Install @notifee/react-native (podinstall)

  • Set up firebaseMessagingService.setBackgroundMessageHandler somewhere in a effect hook, and make sure to call the notifee.incrementBadgeCount() method

import notifee from '@notifee/react-native';
import messaging from '@react-native-firebase/messaging';
const messagingService = messaging();

React.useEffect(() => {
   messagingService.setBackgroundMessageHandler(async (message:    RemoteMessage) => {
        console.log('messagingService.backgroundMessage', message);
        await notifee.incrementBadgeCount();
    });
},[])
Enter fullscreen mode Exit fullscreen mode
  • To reset the badge count to 0, once the app went foreground, use react natives AppState and notifee to do so
import { AppState } from 'react-native';
import notifee from '@notifee/react-native';

AppState.addEventListener('change', (nextAppState) => {
    switch (nextAppState) {
        case 'active': {
            notifee.setBadgeCount(0);
        }
        default:
            return;
    }
});

Enter fullscreen mode Exit fullscreen mode

Done.

Comments 0 total

    Add comment