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
andUserDefaults
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'])
},[])
- 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()
);
Install
@notifee/react-native
(podinstall)Set up
firebaseMessagingService.setBackgroundMessageHandler
somewhere in a effect hook, and make sure to call thenotifee.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();
});
},[])
- 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;
}
});
Done.
Top comments (0)