Search code examples
firebasereact-nativereact-native-firebase

Remove notification after a certain time in React Native (@react-native-firebase/messaging)


I have push notifications working in React Native using @react-native-firebase/messaging. I am using FCM on the backend, and it is currently showing the OS lock screen notifications on iOS and Android.

I want to clear a given notification after a certain time, or after an amount of time has passed. Is there a way to do this? Right now when I send a notification it will stick around for days if I don't click on it. I would like to take a notification down after say an hour, or at 4pm, or whatever. Front-end and/or back-end solutions welcome.

I had assumed that the "ttl" (time to live) parameter did this, but this is not the case.


Solution

  • you could use a background handler like react-native-background-fetch

    In your onMessage or backgroundMessage schedule a backgroundTask for your desired time with scheduleTask().

    You could use react-native-push-notification to display the notification, which has an method cancelLocalNotifications() to cancel notifications In the task you could clear the notification depending on the id

    PushNotification.configure({
      onNotification: (notification) => {
        var {id} = remoteMessage.data
        
        BackgroundFetch.configure({
          minimumFetchInterval: 15
        }, async (taskId) => {
        
          PushNotification().cancelLocalNotifications(id)
          BackgroundFetch.finish(taskId);
        })
        
        BackgroundFetch.scheduleTask({
          taskId: id,
          forceAlarmManager: true,
          delay: 5000 
        });
    
      }
    })