Khaled Boussoffara
Khaled Boussoffara

Reputation: 1771

React Native Firebase 6 cloud messaging and Push notifications

I'm working with react native and firebase 6 to send push notifications. I use the official documentations of the new version : https://invertase.io/oss/react-native-firebase/v6

I add native code for both android and ios to handle sending and receiving notifications

In my AndroidManifest.xml :

<!-- [START firebase_service] -->
        <service
            android:name=".java.MyFirebaseMessagingService"
            android:exported="false">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>
        <!-- [END firebase_service] -->

I did not create the MyFirebaseMessagingService .

I AppDelegate.m i add some functions :

// Required for the register event.
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
  [FIRMessaging messaging].APNSToken = deviceToken;
  [RNCPushNotificationIOS didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];
  NSLog(@"APNs device token retrieved: %@", deviceToken);
}

// Required for the registrationError event.
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
  [RNCPushNotificationIOS didFailToRegisterForRemoteNotificationsWithError:error];
  NSLog(@"Unable to register for remote notifications: %@", error);
}
// Required for the localNotification event.
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
  [RNCPushNotificationIOS didReceiveLocalNotification:notification];
}

In my Component.js i get the token like this :

// Firebase
import firebase from '@react-native-firebase/app'
import messaging from '@react-native-firebase/messaging'

  // ----- COMPONENT DID MOUNT ---- //
  async componentDidMount () {
    // ====================================================== //
    // ====================================================== //
    // ====================================================== //
    const granted = messaging().requestPermission()

    if (granted) {
      console.log('User granted messaging permissions!')
      // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //
      firebase
        .messaging()
        .getToken()
        .then(fcmToken => {
          if (fcmToken) {
            // user has a device token
            console.log('-------- FCM TOKEN -------')
            console.log(fcmToken)
            console.log(JSON.stringify(fcmToken))
            this._setItem(fcmToken)
          } else {
            // user doesn't have a device token yet
            console.log('error')
          }
        })
      // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //
    } else {
      console.log('User declined messaging permissions :(')
    }
    // ====================================================== //
    // ====================================================== //
    // ====================================================== //
  }
  // ----- FIN COMPONENT DID MOUNT ---- //

I send POST request to https://fcm.googleapis.com/fcm/send :

{
 "to" : "token",
 "notification" : {
 "body" : "un nouveau partage",
 "title" : "un partage de contact reçu",
 "priority" : "high",
 "vibration":true,
 "sound": "Enabled",
 "badge":1,
 "requireInteraction": true,
 "click_action": "fcm.ACTION.HELLO"
 },
 "data" : {
 "body" : "nouvelle opportunité",
 "title" : "un nouveau partage",
 "content_available" : true,
 "priority" : "high"
 } 
}

I receive the notification for both android and ios but i can't handle the click action :

I want to redirect to specific route when the user click on the notification .

Upvotes: 1

Views: 3596

Answers (1)

Siraj Alam
Siraj Alam

Reputation: 10025

I haven't used Firebase for notifications, but as you're saying the notifications are working, then the actual issue it seems to me is you want to handle it when your app opens.

So here are the steps you have to follow to get your work done.

  1. Get the data coming in the notification, on the event onNotificationOpened. Check out this link to check if you're getting the notification data.
  2. Next, you want to a specific route on the basis of notification. What I do is, send the type of the screen and id related to that screen to navigate there, ex:
{
    "entity": "Place",
    "id": "123"
}

So, when I receive the notification, I send the data to a switch case factory that navigate to the screen on the basis of info in that data. Something like that.

function navigateToScreen(entity:string, id:string){

   let screenName = "";
   let params = {}

   switch(entity){
      case "Place": 
          screenName = "placeScreen";
          params = {id};
          break;
      default: return;
   }

   // Navigation Service = https://reactnavigation.org/docs/navigating-without-navigation-prop/
   NavigationService.navigate(screenName, params);

}
  1. Now in case you want to run a specific function on the basis of notification, you can do it on the basis of info received. Like in this example I have to make an API req to get the data of that place by id.

const id = props.match.params['id'];

useEffect(() => {
    getThePlaceDetails(id);
}, [id]);

Upvotes: 1

Related Questions