react-native-firebase v6로 푸시 구현하는 방법

react-native-firebase v6 구현방법은 아래 링크를 참조하세요.

rnfirebase.io/messaging/usage

위 공식문서에는 빠진 부분이 있고 잘못된 부분도 있어서 블로그로 정리했습니다.

 

react-native-firebase v5는 모든 모듈(admob, analytics, crashlytics 등)을 포함하고 있어서 앱이 용량이 크고 무거웠습니다. 푸시를 사용하기 위한 설정도 다소 복잡했습니다. 하지만 v6에서는 필요한 모듈만 사용할 수 있고 설정도 무척 간편해졌습니다.

 

먼저 react-native에 대한 기본지식이 있고 컴퓨터에 react-native 개발환경이 구축되어 있음을 전제로 하겠습니다. 그리고 iOS에서 푸시를 받기 위한 설정과 firebase 콘솔에 프로젝트 설정이 모두 되어 있다고 가정하겠습니다. 

 

iOS에서 푸시를 받기 위한 설정은 다음 링크를 참조하세요.

rnfirebase.io/messaging/usage/ios-setup

 

 

 

 

이제 react-native-firebase v6에서 fcm 구현하는 방법을 알려드리겠습니다.

 

 

1> 먼저 터미널에서 다음 명령어를 입력하여 "@react-native-firebase/app"과 "@react-native-firebase/messaging" 모듈을 설치하세요.

 

yarn add @react-native-firebase/app

 

yarn add @react-native-firebase/messaging

 

 

2> 그 다음 ios 폴더로 이동하여 설치를 계속합니다.

 

cd ios/ && pod install

 

 

3> 안드로이드 프로젝트 소스에서 다음을 추가합니다.

 

<프로젝트모듈의 build.gradle>

 

googlePlayServicesVersion = "17.0.0"와 classpath("com.google.gms:google-services:4.3.3") 추가 

 

buildscript {
    ext {
        buildToolsVersion = "29.0.2"
        minSdkVersion = 16
        compileSdkVersion = 29
        targetSdkVersion = 29

        // NOTE: using any of them will work
        googlePlayServicesVersion = "17.0.0"
    }
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath("com.android.tools.build:gradle:3.5.3")
        classpath("com.google.gms:google-services:4.3.3")
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

 

 

<app  모듈의 build.gradle>

 

맨상단에 apply plugin: "com.google.gms.google-services" 추가 

 

apply plugin: "com.android.application"
apply plugin: "com.google.gms.google-services"

import com.android.build.OutputFile

 

 

 

4> iOS 프로젝트 소스에서 다음을 추가합니다.

 

#import <Firebase.h> 와 

  if ([FIRApp defaultApp] == nil) {

     [FIRApp configure];

     [RNFirebaseNotifications configure];

   }

추가

 

 

<AppDelegate.m> 

 

#import <Firebase.h>
...

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  
  
  if ([FIRApp defaultApp] == nil) {
     [FIRApp configure];
     [RNFirebaseNotifications configure];
   }
   
   ...

 

 

 

 

5> 자바스크립트 파일에 다음을 추가합니다.

 

<index.js>

 

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



//백그라운드에서 푸시를 받으면 호출됨 

messaging().setBackgroundMessageHandler(async remoteMessage => {

console.log('Message handled in the background!', remoteMessage);

});

 

 

<App.js>

 

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

...

 

componentDidMount() {

// FCM 권한 요청 

this.requestUserPermissionForFCM()

}

 

/**

* fcm 푸시 처리

*/

 

requestUserPermissionForFCM = async () => {

const authStatus = await messaging().requestPermission();

const enabled =

authStatus === messaging.AuthorizationStatus.AUTHORIZED ||

authStatus === messaging.AuthorizationStatus.PROVISIONAL;

 

if (enabled) {

const token = await messaging().getToken();

 

//푸시 토큰 표시 

console.log('fcm token:', token);

console.log('Authorization status:', authStatus);

this.handleFcmMessage();

} else {

console.log('fcm auth fail');

}

}

 

handleFcmMessage = () => {

 

//푸시를 받으면 호출됨 

const unsubscribe = messaging().onMessage(async remoteMessage => {

Alert.alert('A new FCM message arrived!', JSON.stringify(remoteMessage));

});

 

//알림창을 클릭한 경우 호출됨 

messaging().onNotificationOpenedApp(remoteMessage => {

console.log(

'Notification caused app to open from background state:',

remoteMessage.notification,

);

 

});

 

}

 

 

이제 firebase 콘솔에서 테스트 메시지를 날려보세요. 폰에서 푸시를 받으면 터미널에 로그가 표시될 것입니다.

댓글