Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show notification on foreground react native firebase v6

I am using the latest react native version 0.62 and latest version of react-native-firebase i.e. v6. I am able to get the notification and it working fine on the background but its not displaying on foreground.

Here is the screenshot: enter image description here

And here is my code:

checkPermission = async () => {
    const enabled = await messaging().hasPermission();
    console.log('enabled ******* ',enabled)
    if (enabled) {
      this.getFcmToken();
    } else {
      this.requestPermission();
    }
  };

  getFcmToken = async () => {
    const fcmToken = await messaging().getToken();
    if (fcmToken) {
      console.log('Your Firebase Token is:', fcmToken);
      // this.showAlert('Your Firebase Token is:', fcmToken);
    } else {
      console.log('Failed', 'No token received');
    }
  };

  requestPermission = async () => {
    try {
      await messaging().requestPermission();
      // User has authorised
    } catch (error) {
      // User has rejected permissions
    }
  };

  messageListener = async () => {
    console.log('inside message listener ****** ')

    messaging().onMessage(async remoteMessage => {
      Alert.alert('A new FCM message arrived!', JSON.stringify(remoteMessage));
  };

  showAlert = (title, message) => {
    Alert.alert(
      title,
      message,
      [{ text: 'OK', onPress: () => console.log('OK Pressed') }],
      { cancelable: false },
    );
  };

  componentDidMount() {
    this.checkPermission();
    this.messageListener();
  }
like image 962
Ankush Rishi Avatar asked Apr 26 '20 07:04

Ankush Rishi


People also ask

How do I show notification when an app is in foreground React Native?

So as a solution you can use react-native-push-notification to fire push notification when app in foreground. For android you don't need to follow any native installation steps just install library by this command and then you can fire local push notification as below : Create a file called NotificationController.


2 Answers

By default rnfirebase not supporting displaying notification popup when app is in foreground state as they mentioned here. So push notification pop up only displayed when app is in background state or closed.

So if you want to display push notification on foreground mode also then you have to use extra library which will be display fired push notification as local notification as mention in their documentation.

If the RemoteMessage payload contains a notification property when sent to the onMessage handler, the device will not show any notification to the user. Instead, you could trigger a local notification or update the in-app UI to signal a new notification.

So as a solution you can use react-native-push-notification to fire push notification when app in foreground.

To do so, just install it by command :

npm i react-native-push-notification

For android you don't need to follow any native installation steps just install library by this command and then you can fire local push notification as below : Create a file called NotificationController.android.js :

import React, { useEffect } from 'react';
import { Alert } from 'react-native';
import messaging from '@react-native-firebase/messaging';
import PushNotification from 'react-native-push-notification';

const NotificationController = (props) => {
  useEffect(() => {
    const unsubscribe = messaging().onMessage(async (remoteMessage) => {
      PushNotification.localNotification({
        message: remoteMessage.notification.body,
        title: remoteMessage.notification.title,
        bigPictureUrl: remoteMessage.notification.android.imageUrl,
        smallIcon: remoteMessage.notification.android.imageUrl,
      });
    });
    return unsubscribe;
  }, []);

  return null;
};

export default NotificationController;

Now, when app is in foreground state and if onMessage receive any message from firebase then PushNotification will fire local notification.

Update: For iOS For iOS you have to install @react-native-community/push-notification-ios using this command:

npm i @react-native-community/push-notification-ios

Also follow all the native installation steps as suggested in document.

Then you can create file called NotificationController.ios.js where you can handle notification for iOS.

import { useEffect } from 'react';
import { Alert } from 'react-native';
import messaging from '@react-native-firebase/messaging';
import PushNotification from 'react-native-push-notification';
import PushNotificationIos from '@react-native-community/push-notification-ios';

const NotificationController = (props) => {
  const navigation = useNavigation();
  // Called when application is open by clicking on notification
  // and called when application is already opend and user click on notification

  PushNotification.configure({
    onNotification: (notification) => {
      if (notification) {
        console.log(notification);
        Alert.alert('Opened push notification', JSON.stringify(notification));
      }
    },
  });

  useEffect(() => {
    // Usesd to display notification when app is in foreground
    const unsubscribe = messaging().onMessage(async (remoteMessage) => {
      PushNotificationIos.addNotificationRequest({
        id: remoteMessage.messageId,
        body: remoteMessage.notification.body,
        title: remoteMessage.notification.title,
        userInfo: remoteMessage.data,
      });
    });

    return unsubscribe;
  }, []);

  return null;
};

export default NotificationController;

Now, call <NotificationController /> in you Home screen or App initial routing file.

like image 126
Kishan Bharda Avatar answered Oct 19 '22 23:10

Kishan Bharda


I agree with all the above solutions... I just wanted to add that, if you don't have channel id the use

PushNotification.createChannel(
    {
      channelId: 'fcm_fallback_notification_channel', // (required)
      channelName: 'My channel', // (required)
      channelDescription: 'A channel to categorise your notifications', // (optional) default: undefined.
      soundName: 'default', // (optional) See `soundName` parameter of `localNotification` function
      importance: 4, // (optional) default: 4. Int value of the Android notification importance
      vibrate: true, // (optional) default: true. Creates the default vibration patten if true.
    },
    created => console.log(`createChannel returned '${created}'`),
  );

and be careful while using

const dat = {
      channelId: 'fcm_fallback_notification_channel', // (required)
      channelName: 'My channel',
      //... You can use all the options from localNotifications
      message: notification.body, // (required)
      title: notification.title,
    };
console.log(dat)
PushNotification.localNotification(dat);

In some case when title: undefined, or title: Object{}, same for message might be happening so console log every thing and put it inside localNotification fuction

like image 45
Rahul Shakya Avatar answered Oct 19 '22 23:10

Rahul Shakya