Настройка Notifee для React Native с Firebase

В этой статье мы рассмотрим установку Notifee в React Native.

Я предполагаю, что вы установили и настроили

✔️ @react-native-firebase
✔️ Создали файл Notifications.ts, который работает с Firebase
✔️ Запросили и получили разрешение пользователя
✔️ Подписался на канал
✔️ Созданы слушатели уведомлений в Firebase
✔️ Уведомления с данными могут быть отправлены с бэкенда

Теперь давайте настроим notifee

1- yarn add @notifee/react-native
2- cd ios/ && pod install —repo-update

Теперь создадим функцию handleClickedNotitfaction в NotificationHandler.ts

export const handleClickedNotitfaction = (notification: FirebaseMessagingTypes.RemoteMessage): void => {
  if (notifcation && notification.data && notification.data.type) {
    switch (notification.data.type) {
      case 'Product':
        navigateToProduct({
          navigation: NavigationService,
          id: notification.data.product_id,
          title: notification.data.product_name,
        });
        break;
      case 'Category':
        navigateToCategory({
          navigation: NavigationService,
          id: notification.data.category_id,
          title: notification.data.category_name,
        });
        break;
      case 'Brand':
        navigateToBrand({ navigation: NavigationService, id: notification.data.brand_id, title: notification.data.brand_name });
        break;
      default:
        navigateToHome({ navigation: NavigationService });
    }
  }
};
Вход в полноэкранный режим Выйти из полноэкранного режима

А в файле index.ts установим нашу функцию onBackgroundEvent

import { handleClickedNotitfaction } from './src/utils';
import notifee, { EventType } from '@notifee/react-native';

notifee.onBackgroundEvent(async ({ type, detail }) => {
  switch (type) {
    case EventType.DISMISSED:
      notifee.cancelNotification(detail.notification.id);
      break;
    case EventType.PRESS:
      handleClickedNotitfaction(detail.notification);
      break;
    default:
      break;
  }
});
Войти в полноэкранный режим Выйти из полноэкранного режима

В файле App.tsx настраиваем функцию onForegroundEvent

import { handleClickedNotitfaction } from './utils';
import notifee, { EventType } from '@notifee/react-native';

  useEffect(() => {
    const unsubscribe = () => {
      return notifee.onForegroundEvent(({ type, detail }) => {
        switch (type) {
          case EventType.DISMISSED:
            notifee.cancelNotification(detail.notification.id);
            break;
          case EventType.PRESS:
            handleClickedNotitfaction(detail.notification);
            break;
          default:
            break;
        }
      });
    };

    unsubscribe();
  }, []);
Вход в полноэкранный режим Выйти из полноэкранного режима

Затем создадим функцию onMessageHandler, которая интегрируется с firebase

import notifee from '@notifee/react-native';

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

  notifee.displayNotification({
    id: message.messageId,
    title: message.notification.title,
    body: message.notification.body,
    data: message.data,
    android: {
      channelId: channelId,
      pressAction: {
        id: 'default',
      },
    },
  });
};
Вход в полноэкранный режим Выход из полноэкранного режима

Теперь нам нужно добавить эту функцию в @react-native-firebase/messaging

import messaging from '@react-native-firebase/messaging';

  useEffect(() => {
    const unsubscribe = messaging().onMessage(onNotifeeMessageReceived);

    return unsubscribe;
  }, []);

Вход в полноэкранный режим Выйти из полноэкранного режима

Теперь вы успешно установили @notifee/react-native, а также интегрировали его с @react-native-firebase

Счастливого кодинга ❤

Оцените статью
devanswers.ru
Добавить комментарий