본문 바로가기
개발/RN

[RN] Expo FCM 푸시알림 구현하기 (2)

by devhooney 2024. 6. 4.
728x90

 


 

 

Expo FCM 푸시알림 구현하기!

 

 

설정은 여기서!

[RN] Expo FCM 푸시알림 구현하기 (1) (tistory.com)

 

[RN] Expo FCM 푸시알림 구현하기 (1)

Expo FCM 푸시알림 구현하기!   1. 라이브러리 설치npm i expo-notificationsnpm i @react-native-firebase/messaging   2. FCM 토큰 받기 /** * FCM 토큰을 받습니다. */ const getFcmToken = async () => { const fcmToken = await messagi

devhooney.tistory.com

 

 

 

지난번 포스팅에서 토큰 받고, 설정해서 테스트까지 진행했다.

이번엔 코드 작성을 해보면

 

먼저 앱은 Foreground, Background, quit 상태로 나뉜다.

Background는 홈버튼이나 다른앱을 실행해서 앱이 완전히 종료되지 않은 상태.

Quit는 앱을 완전히 종료한 상태

 

 

1. App.js 는 Expo로 프로젝트 구성시 처음 실행되는 화면

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

messaging().setBackgroundMessageHandler(async remoteMessage => {
    console.log('Background & Quit');
    await schedulePushNotification(remoteMessage);
});


export default function App(props) {
    return (
        <></>
    );
}

 

- background, quit 상태일 때 푸시알림을 받기 위한 설정

 

 

 

 

 

728x90

 

 

 

 

 

 

2. 초기화

import React, {useEffect, useRef, useCallback, useState} from 'react';
import messaging from '@react-native-firebase/messaging';
import schedulePushNotification from './schedulePushNotification';


export default function TestProj(props) {
  const webviewRef = useRef(null);
  const [returnUrl, setReturnUrl] = useState("");
  const [pushToken, setPushToken] = useState('');
  
  // 권한, fcm 관련 초기화
  useEffect(() => {
  	requestNotificationPermission();
    setToken(setPushToken, webviewRef);
    setMessage();
  }, []);
  
  const requestNotificationPermission = async () =>  {
    const settings = await Notifications.requestPermissionsAsync();
  }
  
  const setToken = async (setPushToken, webviewRef) =>  {
    messaging().getToken().then(token => {
        console.log('Device FCM Token:', token);
    });
  }
  
  const setMessage = async () =>  {
    const unsubscribe = messaging().onMessage(async remoteMessage => {
        console.log('Foreground')
        await schedulePushNotification(remoteMessage);
    });
    return unsubscribe;
  }

 

 

 

3. 알림 보내기 함수

import * as Notifications from 'expo-notifications';

Notifications.setNotificationHandler({
  handleNotification: async () => ({
    shouldShowAlert: true,
    shouldPlaySound: true,
    shouldSetBadge: true,
  }),
});



export default schedulePushNotification = async (remoteMessage) =>  {

  
  await Notifications.setNotificationChannelAsync('default', {
      name: 'default',
      importance: Notifications.AndroidImportance.MAX,
      vibrationPattern: [0, 250, 250, 250],
      lightColor: '#FF231F7C',
  });
    
  await Notifications.scheduleNotificationAsync({
    content: {
      title: remoteMessage.notification?.title || remoteMessage.data.title,
      body: remoteMessage.notification?.body || remoteMessage.data.body,
    },
    trigger: {
      seconds: 1,
      channelId: 'default', // <- for Android 8.0+, see definition above
    },
  });
}

 

- 실제 스마트폰의 상단에 알림을 주는 함수.

 

 

 

이렇게 하면 실제로 요청을 했을 때 알림을 받을 수있다.

다음 포스팅에서 요청하는 코드를 작성한다.

 

 

 

 

728x90

'개발 > RN' 카테고리의 다른 글

[RN] Expo FCM 푸시알림 구현하기 (1)  (143) 2024.05.30
[RN] WebView와 Web 통신하기  (184) 2024.05.17
[RN] expo eas 관련 명령어 정리  (203) 2024.05.09
[RN] expo 앱 테스트 하기  (188) 2024.04.25
[RN] WebView 뒤로가기 구현하기  (123) 2024.01.30