💬 푸시 알림을 구현 중 엄청난 억까를 겪음
💡 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로 개발 환경 변경 후 성공함
시작하기 클릭
프로젝트 추가 -> 앱추가 클릭
Andoird 패키지 이름이 가장 중요함
나는 앱 프로젝트 이름을 fcm으로 만들어서 패키지 이름 com.fcm으로 설정
그 후 구성 파일 다운로드 하면 이런 파일이 받아짐
android/app 안에 넣기
npm install @react-native-firebase/app
npm install @react-native-firebase/messaging
// /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") // <-- 추가
}
// /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' // <-- 추가
}
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;
// index.js
import messaging from '@react-native-firebase/messaging';
messaging().setBackgroundMessageHandler(async remoteMessage => {
console.log('background: ', remoteMessage);
});()
백그라운드는 app 밖의 코드에 적어줘야해서 index.js에 해야함
- messaging().getToken() FCM 토큰 얻음
- messaging().onMessage() 포어그라운드 메시지
- messaging().setBackgroundMessageHandler() 백그라운드 메시지
이렇게 하면 무사히 FCM 기능이 됨