React-native with Firebase FCM not working

7.5k views Asked by At

I have done the following changes:

How is send notifications, using firebase-admin and getting successful result:

admin.messaging().sendToDevice(
        "token as string",
        {
        notification: {
            title: 'title here',
            body: 'body here'
            }
        },
        {
            priority: "high",
            contentAvailable: true,
            timeToLive: 2419200
        });

React-native code, this is when the application is in the foreground:

useEffect(() => {
    checkToken().then((token) => {
      console.log(token);
      // write to db
    });
    const unsubscribe = messaging().onMessage(async (remoteMessage) => {
      console.log(remoteMessage);
    });
    return unsubscribe;
  }, []);

I have the GoogleService-Info.plist file in the ios folder, I have uploaded the APNs in the firebase console + teamid + appid.

Following changes in AppDelegate.m:

#import <Firebase.h>
....
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{

[FIRApp configure];

I am not receiving any notification while the app runs in the foreground, there must be something wrong with the way I am sending (probably I have the wrong options) or, what I have in react-native is wrongly configured, not sure. I am trying to do it only for IOS for now.

Any info or solution would be helpful.

5

There are 5 answers

0
Nicolae Maties On BEST ANSWER

I eventually fixed it by running a clean run on an actual device.

7
Akshay Shenoy On

React native firebase do not show notification when the app is in foreground, so what I have done is, I am using a different library to handle foreground notification. I am using react-native-push-notification.\

For Android

import PushNotification from 'react-native-push-notification';
import PushNotificationIos from '@react-native-community/push-notification-ios';

useEffect(() => {
    checkToken().then((token) => {
      console.log(token);
      // write to db
    });
    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;
  }, []);

For iOS: For iOS you have to install @react-native-community/push-notification-ios
Also follow all the native installation steps as suggested in document. Then write the following code

PushNotification.configure({
    onNotification: (notification) => {
      if (notification) {
        console.log(notification);
      }
    },
  });

  useEffect(() => {
    // To display notification when app is in foreground
    const unsubscribe = messaging().onMessage(async (remoteMessage) => {
      PushNotificationIos.addNotificationRequest({
        message: remoteMessage.notification.body,
        title: remoteMessage.notification.title,
        bigPictureUrl: remoteMessage.notification.android.imageUrl,
        smallIcon: remoteMessage.notification.android.imageUrl,
      });
    });

    return unsubscribe;
  }, []);
1
Amit Dutta On

1st you need to get the messaging permission

async function requestUserPermission() {
    const authStatus = await messaging().requestPermission();
    const enabled =
      authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
      authStatus === messaging.AuthorizationStatus.PROVISIONAL;
  
    if (enabled) {
      console.log('Authorization status:', authStatus);
    }
}

Then you need to create a channel:

const createFCMChannel = async () => {
    const channelId = await notifee.createChannel({
      id: 'default',
      name: 'Default Channel',
    });
};

You can just call this method which will call "displayNotification" from notifee

function onMessageReceived(message) {
    notifee.displayNotification(message.notification);
}

you can use these methods in useEffect when your app starts:

useEffect(() => {
    createFCMChannel();
}, []);

useEffect(() => {
    requestUserPermission();
    messaging().onMessage(onMessageReceived);
    messaging().setBackgroundMessageHandler(onMessageReceived);
}, []); 
0
Elmar On

You can control and print notification data directly from AppDelegate file. It allows quicker debugging process as you bypass your app logic and play with the data at the first incoming door. This way, you will find out where is the problem - server side (notification data structure etc.) or app logic/local handling process. Just play with this sample code part in Appdelegate.m file:

Messaging.messaging().appDidReceiveMessage(userInfo) 

  With swizzling disabled you must let Messaging know about the message, for Analytics
  [[FIRMessaging messaging] appDidReceiveMessage:userInfo];
  FIRMessaging.messaging().appDidReceiveMessage(userInfo);
  Messaging.messaging().delegate = self
        completionHandler(.NoData)
          [[FIRMessaging messaging] appDidReceiveMessage:userInfo];

  ...

  // Print full message.
  NSLog(@"%@", userInfo);

And as a rule of thumb, check this from Apple developer page about structure and parameters: https://developer.apple.com/documentation/uikit/uiapplicationdelegate/1622921-application

1
AudioBubble On

There are several things to solve this issue

  1. You can check whether the notifican permission is granted or not?
  2. Check if you have set the both foreground and background notifications?
  3. Uninstall the app and reinstall it.
  4. Clean run with real device.