간단하지만 이 간단한 거 해결하는데 몇 시간이 걸렸다.
나는 프론트엔드를 할 줄 모르기 때문이다...
사전 설치 및 설정
react native 설치하는 방법은 인터넷에 많으므로 생략하겠다.
node.js 사용해서 이렇게 저렇게 설치하면 된다.
안드로이드를 사용할 것이기 때문에 안드로이드 스튜디오도 설치하고 안드로이드 에뮬레이터도 같이 설치한다.
에뮬레이터 없이 휴대폰으로 하는 방법도 있었던 것 같은데 보안때문에 이것저것 해야했던 것으로 기억한다.
그리고 파이어베이스 콘솔에서 안드로이드 앱도 만들어준다.
프로젝트 설정에서 만들 수 있고 만들면

이렇게 나오는데 google-services.json 파일이 나중에 필요하므로 다운로드해 준다.
패키지 이름도 나중에 필요하다.
프로젝트 시작
react native가 구 버전이라면 아마
npx react-native init [프로젝트명]
명령어를 사용할 수 있을 것 같은데 나는
⚠️ The `init` command is deprecated.
The behavior will be changed on 2024. 12. 31. (15 days).
- Switch to npx @react-native-community/cli init for the identical behavior.
- Refer to the documentation for information about alternative tools: https://reactnative.dev/docs/getting-started
Running: npx @react-native-community/cli init
node:events:502
throw er; // Unhandled 'error' event
^
Error: spawn npx ENOENT
at ChildProcess._handle.onexit (node:internal/child_process:285:19)
at onErrorNT (node:internal/child_process:483:16)
at process.processTicksAndRejections (node:internal/process/task_queues:90:21)
Emitted 'error' event on ChildProcess instance at:
at ChildProcess._handle.onexit (node:internal/child_process:291:12)
at onErrorNT (node:internal/child_process:483:16)
at process.processTicksAndRejections (node:internal/process/task_queues:90:21) {
errno: -4058,
code: 'ENOENT',
syscall: 'spawn npx',
path: 'npx',
spawnargs: [ '@react-native-community/cli@latest', 'init', 'My' ]
}
이런 오류가 나와서
npx @react-native-community/cli init [프로젝트명]
명령어를 사용해 init 해주었다.
12월 31일부터 바뀐다고 하니 밑의 명령어를 사용하는 것이 좋겠다.
그리고 cd 명령어로 해당 프로젝트로 이동한 후
yarn add @react-native-firebase/app
yarn add @react-native-firebase/messaging
이 두 개의 명령어를 실행한다.
토큰만 얻는 거라면 밑의 명령어는 필요 없을 것 같긴하다.
나는 FCM을 사용할 것이라 밑의 명령어도 실행했다.
만든 프로젝트를 적당한 IDE를 사용해 열어보자.
나는 Visual Code 사용해서 열었다.
그러면 밑의 사진과 같은 프로젝트 구조가 보일 것이다.

프로젝트 설정

여기에 있는 SDK 안내 보기 버튼을 눌러 따라하면 된다.

나는 사진과 약간 경로가 달랐다.

MyApp/android/app 안에 넣어주었다.

다음 단계는 이건데 나는 여전히 buildscript를 사용해서

이 경로의 build.gradle에
dependencies {
classpath("com.android.tools.build:gradle")
classpath("com.facebook.react:react-native-gradle-plugin")
classpath("org.jetbrains.kotlin:kotlin-gradle-plugin")
classpath("com.google.gms:google-services:4.4.2")
}
이렇게 넣어주었다.
!그리고 패키지 이름을 맞춰줘야 한다!

여기 있는 applicationId를 파이어베이스 콘솔의 패키지 이름과 맞춰주자.

그리고 android/app/build.gradle에는 (사진의 경로이다)
맨 위에
apply plugin: "com.google.gms.google-services"
이걸 넣어주고
dependencies 에는
implementation platform('com.google.firebase:firebase-bom:33.7.0')
implementation 'com.google.firebase:firebase-analytics'
implementation 'com.google.firebase:firebase-messaging'
이걸 넣어주었다.
형식이 똑같은 애들끼리 모여있기 때문에 형식 보고 넣어주면 되겠다.
구글 SDK 안내에 친절하게 잘 나와있으니 그거 보고 해도 된다.
코드 작성

이 경로에 있는 App.tsx에
import React, { useEffect } from 'react';
import messaging from '@react-native-firebase/messaging';
const App = () => {
useEffect(() => {
requestPermission();
getFcmToken();
// 앱이 백그라운드 상태일 때 메시지를 처리할 핸들러 설정
messaging().setBackgroundMessageHandler(async remoteMessage => {
console.log('[+] Background Message: ', JSON.stringify(remoteMessage));
});
// 메시지 수신 구독
const unsubscribe = subscribe();
return () => {
unsubscribe(); // 이벤트 리스너 해제
};
}, []);
// 권한 요청
const requestPermission = async () => {
const authStatus = await messaging().requestPermission();
const enabled =
authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
authStatus === messaging.AuthorizationStatus.PROVISIONAL;
if (enabled) {
console.log('[+] Notification Permission granted');
} else {
console.warn('[-] Notification Permission denied');
}
};
// FCM 토큰 받기
const getFcmToken = async () => {
try {
const fcmToken = await messaging().getToken();
console.log('[+] FCM Token :: ', fcmToken);
} catch (error) {
console.error('[-] Error getting FCM Token: ', error);
}
};
// 메시지 처리
const subscribe = () => {
return messaging().onMessage(async remoteMessage => {
try {
console.log('[+] Remote Message ', JSON.stringify(remoteMessage));
} catch (error) {
console.error('[-] Error handling remote message: ', error);
}
});
};
return <></>;
};
export default App;
이렇게 작성해준다.
-> 오류가 있어 수정하였음.
프로젝트 실행
프로젝트가 있는 경로로 이동하여
npx react-native run-android
명령어를 실행한다.
npx react-native start --reset-cache
오류가 난다면 이런 식으로 캐시를 지우고 실행해보자.
나는 노트북이라 그런지 실행이 꽤 오래 걸리긴 했지만 잘 실행되었다.
앱이 실행되고 나면 터미널에 토큰이 나온다!
'프로그래밍 > AOS' 카테고리의 다른 글
[구글 플레이 콘솔] '결제 프로필에 문제가 있음'과 앱 이전 과정 (2) (2) | 2024.02.08 |
---|---|
[구글 플레이 콘솔] '결제 프로필에 문제가 있음'과 앱 이전 과정 (5) | 2024.02.06 |