[React Native] 푸시 알림 - FCM

네민·2023년 9월 26일
0
post-thumbnail

💬 푸시 알림을 구현 중 엄청난 억까를 겪음
💡 React Native CLI로 프로젝트 개발 환경 변경 후 해결

1. Expo bare workflow -> React Native CLI

졸작 구현 중 expo -> expo bare workflow로 환경을 변경함

fcm 토큰을 받기 위해 이것저것 해보았으나

Error: You attempted to use a firebase module that's not installed on your Android project by calling firebase.app().

Ensure you have:

1) imported the 'io.invertase.firebase.app.ReactNativeFirebaseAppPackage' module in your 'MainApplication.java' file.

2) Added the 'new ReactNativeFirebaseAppPackage()' line inside of the RN 'getPackages()' method list.

See http://invertase.link/android for full setup instructions., js engine: hermes
 ERROR  Invariant Violation: "main" has not been registered. This can happen if:
* Metro (the local dev server) is run from the wrong folder. Check if Metro is running, stop it and restart it in the current project.
* A module failed to load due to an error and `AppRegistry.registerComponent` wasn't called., js engine: hermes

이 오류가 사라지지 않았음

검색해보면 새로 빌드를 하라는 말이 있었으나, 해도 같은 오류가 떴음

-> 결국 포기하고 React Native CLI로 개발 환경 변경 후 성공함

2. Firebase 설정


시작하기 클릭

프로젝트 추가 -> 앱추가 클릭

Andoird 패키지 이름이 가장 중요함
나는 앱 프로젝트 이름을 fcm으로 만들어서 패키지 이름 com.fcm으로 설정

그 후 구성 파일 다운로드 하면 이런 파일이 받아짐

android/app 안에 넣기


3. Firebase 설치

1. 설치

npm install @react-native-firebase/app
npm install @react-native-firebase/messaging

2. android 폴더 안의 build.gralde

 // /android/build.gradle
 
 dependencies {
        classpath("com.android.tools.build:gradle")
        classpath("com.facebook.react:react-native-gradle-plugin")
        classpath("com.google.gms:google-services:4.3.14") // <-- 추가
    }

3. android/app 폴더 안의 build.gralde

 // /android/app/build.gradle
 
apply plugin: "com.google.gms.google-services" <-- 추가

... 

dependencies {

    implementation platform('com.google.firebase:firebase-bom:31.1.0') // <-- 추가
    implementation 'com.google.firebase:firebase-messaging' // <-- 추가
}

4. 메세지 수신 & 토큰 발급 코드

1. 포어그라운드 & 토큰 버튼

import React, {useEffect, useState} from 'react';
import {View, Button} from 'react-native';
import messaging from '@react-native-firebase/messaging';


const App = () => {
  const [fcmToken, setFcmToken] = useState('');

 useEffect(() => {
    const unsubscribe = messaging().onMessage(async remoteMessage => {
      console.log('foreground:', remoteMessage);
      // 여기에서 메시지를 처리하고 화면에 표시할 수 있습니다.
    });

    return unsubscribe;
  }, []);


  const getFcmToken = async () => {
    const token = await messaging().getToken(); // <-- 토큰 얻음
    console.log('[FCM Token]', token);
    setFcmToken(token);
  };

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

  return (
    <View>
      <Button title="Send Token to Server" onPress={FcmToken} />
    </View>
  );
};

export default App;

2. 백그라운드

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

messaging().setBackgroundMessageHandler(async remoteMessage => {
  console.log('background: ', remoteMessage);
});()

백그라운드는 app 밖의 코드에 적어줘야해서 index.js에 해야함

  1. messaging().getToken() FCM 토큰 얻음
  2. messaging().onMessage() 포어그라운드 메시지
  3. messaging().setBackgroundMessageHandler() 백그라운드 메시지

이렇게 하면 무사히 FCM 기능이 됨

📖 참고 | React-Native에서 FCM을 통한 알림 수신하기(Android)

profile
기록하자

0개의 댓글