sanguk.dev
작성완료
React Native 푸쉬 사용

React Native 푸쉬 사용

React Native에서 푸시 알림을 사용하기 위한 모듈 설치 방법, Info.plist 및 AppDelegate.swift 설정, 사용 예제와 Node.js 서버에서의 푸시 알림 전송 방법을 설명합니다. Firebase 모듈을 설치하고, 권한 요청 및 토큰 획득, 알림 수신 핸들링을 포함한 코드 예시가 제공됩니다.

React Native@react-native-firebase/app@react-native-firebase/messaging

앱 (React Native)

1. 모듈 설치

shell
yarn add @react-native-firebase/app @react-native-firebase/messaging

iOS는 cd ios && pod install && cd ..

2. Info.plist

xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  ...
  <key>UIBackgroundModes</key>
	<array>
		<string>remote-notification</string>
	</array>

	<key>FirebaseAppDelegateProxyEnabled</key>
	<false/>
  ...
</dict>
</plist>

3. AppDelegate.swift

swift
import UIKit
import React
import React_RCTAppDelegate
import ReactAppDependencyProvider

import Firebase  // ✅ 추가
import UserNotifications  // ✅ 추가

@main
class AppDelegate: RCTAppDelegate, UNUserNotificationCenterDelegate, MessagingDelegate {
  override func application(
	  _ application: UIApplication, 
	  didFinishLaunchingWithOptions launchOptions: 
	  [UIApplication.LaunchOptionsKey : Any]? = nil
  ) -> Bool {
    self.moduleName = "프로젝트명"
    self.dependencyProvider = RCTAppDependencyProvider()

    self.initialProps = [:]

    // ✅ 추가
    if FirebaseApp.app() == nil {
      FirebaseApp.configure()
    }
    Messaging.messaging().delegate = self
    
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }

  // ✅ 추가
  override func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
      Messaging.messaging().apnsToken = deviceToken
      print("✅ APNS 토큰 등록 완료")
  }
  // ✅ 추가
  override func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
      print("❌ APNS 등록 실패: \(error)")
  }
  // ✅ 추가
  func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
      print("✅ FCM 토큰: \(fcmToken ?? "")")
      // 서버에 토큰 전송 등 추가 작업 가능
  }

}

4. 사용

typescript
// ✅ usePush.ts

import messaging from '@react-native-firebase/messaging';
import {useEffect} from 'react';

export default (): void => {
  useEffect(() => {
    // 권한 요청
    messaging()
      .requestPermission()
      .then(authStatus => {
        const enabled =
          authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
          authStatus === messaging.AuthorizationStatus.PROVISIONAL;

        if (enabled) {
          console.log('Push Authorization: OK');
        }
      });

    // 토큰 얻기
    messaging()
      .getToken()
      .then(token => {
        console.log('FCM Token: ', token);
      });

    // 알림 수신 핸들링
    const unsubscribe = messaging().onMessage(async remoteMessage => {
      // Alert.alert(
      //   remoteMessage.notification?.title || '',
      //   remoteMessage.notification?.body || '',
      // );
      console.log(
        remoteMessage.notification?.title,
        remoteMessage.notification?.body,
      );
    });

    return unsubscribe;
  }, []);
};

typescript
// ✅ index.ts

export default () => {
  usePush();

  return <App />;
};

서버 (NodeJS)

1. 모듈 설치

bash
pnpm i firebase-admin

2. 사용

typescript
// ✅ main.ts

import admin from 'firebase-admin';
import * as serviceAccount from './serviceAccountKey.json';

const credential = admin.credential.cert(serviceAccount);
admin.initializeApp({ credential });

const sendNotification = (token: string, title: string, body: string) => {
  const message = admin.messaging();
  const notification = { title, body };
  await message.send({ token, notification });
}

// ✅ 푸쉬 전송
// sendNotification('ABCDE-ABCDE-ABCDE-ABCDE', '푸쉬 테스트', '테스트용 푸쉬입니다.');