ReactNative - [ios/android] notifee 설정

nueiin·2024년 1월 15일

React Native

목록 보기
3/7

1. 고려해야할 사항

  • foreground / background
    처리해야할 이벤트
    예) 딥링크를 이용한 앱 실행 또는 notification 삭제
  • android / ios
    알림에 대한 설정(사운드, 아이콘 등)

2. 구현

index.js

...
const Navigation () => {
	...
  	// noti
    useEffect(() => {
        notifee.onForegroundEvent(async ({ type, detail }) => {
            console.log("App.js notifee onForegroundEvent==============");
            if (type === EventType.PRESS) {
                // 처리할 이벤트 추가
            } else if (type === EventType.DISMISSED) {
            	// noti 삭제
                notifee.cancelNotification(detail.notification.id);
                notifee.cancelDisplayedNotification(detail.notification.id);
            }
        });
        
        notifee.onBackgroundEvent(async ({ type, detail }) => {
            console.log("App.js notifee onBackgroundEvent==============");
            if (type === EventType.PRESS) {
                // 처리할 이벤트 추가
            } else if (type === EventType.DISMISSED) {
            	// noti 삭제
                notifee.cancelNotification(detail.notification.id);
                notifee.cancelDisplayedNotification(detail.notification.id);
            }
        });
    
        messaging().setBackgroundMessageHandler(async (remoteMessage) => {
            console.log("App.js setBackgroundMessageHandler=========");
            console.log(remoteMessage);
            await PushNoti.displayNoti(remoteMessage);
        });
        
        messaging().onMessage(async remoteMessage => {
            let chat_id = '';
            let topic_id = '';
            console.log("App.js onMessage ====================");
            chat_id = remoteMessage.data.chat_id;
            topic_id = remoteMessage.data.topic_id;

            let current_chat_id = navigationRef?.getCurrentRoute().params?.chat_id;
            let current_topic_id = navigationRef?.getCurrentRoute().params?.topic_id;

            if ((current_chat_id !== chat_id) && (current_topic_id !== topic_id)) {
                await PushNoti.displayNoti(remoteMessage);
            }
        });
    }, []);
  	...
}

PushNoti.js

import { Platform } from 'react-native';
import notifee, { AndroidImportance } from '@notifee/react-native';

const displayNotification = async message => {
    var id = undefined;
    if (message.data.data === undefined || message.data.data === null) {
        if (message.data.chat_id !== '_') {
            id = message.data.chat_id;
        } else if (message.data.topic_id !== '_') {
            id = message.data.topic_id;
        }
    } else {
        id = message.data.data.filePath;
    }

    if (Platform.OS !== 'ios') {  // ANDROID
        await notifee.createChannel({
            id: id,
            name: name,
            importance: AndroidImportance.HIGH,
            sound: 'sound'
        }).then(async result => {
            await notifee.displayNotification({
                id: id,
                title: message.data.title,
                body: message.data.body,
                android: {
                    channelId: result,
                    smallIcon: 'ic_stat_name',
                    color: '#5E9441',
                    sound: 'sound',
                    timestamp: Date.now(),
                    showTimestamp: true,
                },
                chat_id: message.data.chat_id,
                topic_id: message.data.topic_id,
                data: message.data
            });
        })
    } else {  // IOS
        notifee.displayNotification({
            id: id,
            title: message.data.title,
            body: message.data.body,
            chat_id: message.data.chat_id,
            topic_id: message.data.topic_id,
            data:message.data,
            ios: {
                sound: 'default',
            }
        });
    }
};

export default {
    displayNoti: remoteMessage => displayNotification(remoteMessage),
};

id를 설정해준 이유는 새로운 메시지를 수신했을 때 id를 이용하여 해당 notification을 최근 수신한 메시지로 업데이트 해주기 위함이다.


참고

https://notifee.app/react-native/docs/overview
https://notifee.app/react-native/docs/displaying-a-notification#updating-a-notification

profile
풀스택 개발자

0개의 댓글