Notice
Recent Posts
Recent Comments
Link
«   2025/10   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

개발자 도전기

[React Native] Firebase 푸시알림 클릭 이벤트 구현하기 본문

개발공부/React

[React Native] Firebase 푸시알림 클릭 이벤트 구현하기

jnnjnn 2025. 8. 6. 00:04

 

파이어베이스에서 푸시알림을 보내는 예제는 많은데, 푸시알림을 클릭하면 특정 페이지로 이동하는 예제는 별로 없어서 공유해본다!

 

1. NavigationRef 등록

특정 페이지로 네비게이트하기 위해 네비게이션을 사용해야 하는데

가장 최상단인 App.tsx 컴포넌트에서는 useNavigation을 사용할 수 없기 때문에 NavigationRef를 사용한다

 

RootNavigation.ts 작성

export const navigationRef = createRef();

export function navigate(name, params) {
    navigationRef.current?.navigate(name, params);
}

 

그리고 App에 import 해서 사용한다

import { navigationRef, navigate } from './RootNavigation';

const App = () => {

	return (
    	<NavigationContainer ref={navigationRef}>
        	<Interceptors />
        </NavigationContainer>
    )
}

 

 

2. 백그라운드 푸시알림 클릭 이벤트 핸들링

 

기본적으로 백그라운드에서 알림을 수신했을 때, 다음처럼 알림 객체를 확인해 볼 수 있다.

messaging().setBackgroundMessageHandler(async remoteMessage => {
  console.log('🕶️ 백그라운드 메시지 수신:', remoteMessage);
  }
});

 

사용자가 푸시 알림을 클릭했을 때 작동하는 핸들러

notifee 사용할 필요 없이 파이어베이스에서 제공하는 메서드 사용하면 된다 !

https://rnfirebase.io/reference/messaging#onNotificationOpenedApp

 

messaging | React Native Firebase

Copyright © 2017-2020 Invertase Limited. Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 3.0 License, and code samples are licensed under the Apache 2.0 License. Some partial documentation, under the

rnfirebase.io

 

프로젝트가 등록되면 해당 프로젝트의 id를 받아서 네비게이트 시켜주었다.

useEffect(() => {
    const unsubscribeNotificationOpen = messaging().onNotificationOpenedApp(remoteMessage => {
      console.log('Firebase 알림 클릭으로 앱이 열림 (백그라운드에서):', remoteMessage);
      
      const projectId = remoteMessage.data?.projectId;
      
      if (projectId) {
        console.log('projectId:', projectId);
        navigate(ProjectRoutes.PROJECT_INFO, { project_id: projectId });
      }
    });

    return unsubscribeNotificationOpen;
  }, [])

 

 

3. 포그라운드 푸시알림 클릭 이벤트 핸들링

 

FCM 토큰을 서버로 보내 파이어베이스에서 푸시알림을 수신하게 되면 백그라운드에서는 푸시알림이 오지만 포그라운드에서는 오지 않는다.

 

이때는 포그라운드에서 알림을 받으면 notifee를 사용해 푸시알림이 가게 했다.

안드로이드 실물 기기에서는 채널 등록을 하지 않으면 알림이 오지 않아서 notifee.createChannel()도 등록했다.

useEffect(() => {
    const unsubscribe = messaging().onMessage(async remoteMessage => {
      console.log('📲 포그라운드 메시지 수신:', remoteMessage);
      
      const projectId = remoteMessage?.data?.projectId
      
      await notifee.createChannel({
        id: 'default',
        name: '기본 알림',
        importance: AndroidImportance.HIGH,
      });

      return notifee.displayNotification({
        data: { projectId: projectId ?? '' },
        title: remoteMessage?.notification?.title,
        body: remoteMessage?.notification?.body,
        android: {
              channelId: 'default',
           	  // 알림을 눌렀을 때 id 설정
              pressAction: {
                id: 'PRESS',
              },
              // 자동으로 앱을 열도록 설정
              autoCancel: true,
            },
            ios: {
              categoryId: 'default',
            }
      })
    });

    return unsubscribe;
  }, []);

 

notifee 알림 클릭시 핸들링하는 메서드도 추가해준다

useEffect(() => {
    const unsubscribeForeground = notifee.onForegroundEvent(async ({ type, detail }) => {
      const projectId = detail.notification?.data?.projectId;

      if (type === EventType.PRESS) {
          navigate(ProjectRoutes.PROJECT_INFO, { project_id: projectId });
      }
    });

    return () => {
      if (unsubscribeForeground) {
        unsubscribeForeground();
      }
    }
  }, []);

 

 

끗!

deepLink를 사용하는 방법보다 더 간단하게 구현할 수 있었다