[React Native] Firebase Push 알림 구현 하기 [ios]


🔥 1. Firebase 프로젝트 생성

(https://console.firebase.google.com/u/0/?hl=ko)

npm i @react-native-firebase/analytics @react-native-firebase/app @react-native-firebase/messaging

npm i react-native-push-notification @react-native-community/push-notification-ios

npm i -D @types/react-native-push-notification

npx pod-install

🔥 2. iOS 프로젝트 추가

2-1 구성 파일 다운로드

  • GoogleService-Info.plist 파일 저장

2-2 Firebase SDK 추가

  • GoogleService-Info.plist 로컬에 파일 저장

2-3 초기화 코드 추가하기

AppDelegate.h

#import <RCTAppDelegate.h>
#import <UIKit/UIKit.h>
#import <UserNotifications/UNUserNotificationCenter.h>

//수정
**@interface** AppDelegate : RCTAppDelegate <UNUserNotificationCenterDelegate>
**@end**

AppDelegate.mm

#import "AppDelegate.h"
#import <React/RCTBundleURLProvider.h>
//스플래시
#import "RNSplashScreen.h"
//FireBase
#import <Firebase.h>
//Push 알림
#import <UserNotifications/UserNotifications.h>
#import <RNCPushNotificationIOS.h>
//코드 푸시
#import <CodePush/CodePush.h>
//Appcenter
#import <AppCenterReactNative.h>
#import <AppCenterReactNativeAnalytics.h>
#import <AppCenterReactNativeCrashes.h>

@implementation AppDelegate

// 등록 이벤트에 필요합니다.
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
 [RNCPushNotificationIOS didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];
}

// 알림 이벤트에 필요합니다. 원격 알림 처리 후 반드시 완료 핸들러를 호출해야 합니다.
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
  [RNCPushNotificationIOS didReceiveRemoteNotification:userInfo fetchCompletionHandler:completionHandler];
}

// 등록 오류 이벤트에 필요합니다.
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
 [RNCPushNotificationIOS didFailToRegisterForRemoteNotificationsWithError:error];
}

// 로컬 알림 이벤트에 필요합니다.
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
didReceiveNotificationResponse:(UNNotificationResponse *)response
         withCompletionHandler:(void (^)(void))completionHandler
{
  [RNCPushNotificationIOS didReceiveNotificationResponse:response];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  // 파이어베이스 초기값 설정
  if ([FIRApp defaultApp] == nil) {
    [FIRApp configure];
  }

  self.moduleName = @"myappname";
  // 아래 사전에 사용자 정의 초기 프로퍼티를 추가할 수 있습니다.
  // 프로퍼티들은 React Native에서 사용되는 ViewController로 전달
  self.initialProps = @{};
  [super application:application didFinishLaunchingWithOptions:launchOptions];
  //스플래시 스크린
  [RNSplashScreen show];
  //파이어베이스 등록 설정
  //사용자 알림 센터
  UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
  center.delegate = self;

  return [super application:application didFinishLaunchingWithOptions:launchOptions];
}

//알림이 포그라운드 앱에 전달될 때 호출.
-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler
{
  completionHandler(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge);
}

- (NSURL *)sourceURLForBridge:(RCTBridge *)bridge
{
#if DEBUG
  return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index"];
#else
  //기존 bundle 설정
	return [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];
  //code push bundle 설정
#endif
}

@end

Podfile 수정

#Podfile

# 파이어베이스 추가
  pod 'FirebaseCore', :modular_headers => true
  # Add the Firebase pod for Google Analytics 애널래틱스
  pod 'FirebaseAnalytics'
  # Add the Firebase pod for message 메시지알림
  pod 'FirebaseMessaging'

🔥 3. iOS 푸시메시지 활성화하기

3-1 xcode 수정하기

  • Signing & Capabilities에서 Background Modes의 Background fetch , Remote notifications 체크
  • 우상단 +버튼 클릭 후 Push Notifications를 활성화

3-2 키체인 다운로드

  • macOS에서 키체인접근 ⇒ 인증서 지원 ⇒ 인증기관에서 인증서 요청 ⇒ 이메일 입력후 디스크에 저장됨 , 본인이 키페어 정보 지정 ⇒ 저장하기

3-3 APN key 등록하기

  • Key Name 입력 후Apple Push Notifications service (APNs) 체크 (https://developer.apple.com/account/resources/authkeys/add)

🔥 4. Firebase 프로젝트 설정

4-1 APN 인증키 Firebase에 등록하기

  • Firebase 프로젝트 설정 ⇒ 클라우드 메시징 탭 ⇒ Apple 앱 구성 항목에서 APN 인증 키 ex) AuthKey_sfdfsdfd!!.p8 파일 등록
  • 키 ID 등록 3-4에서 등록했던 APN 키 ID를 입력
  • 팀 ID는 Apple Member Center에 멤버십 등록을 하면 확인할 수 있음

4-2 Identifiers 생성하기

  • Identifiers 생성 APP IDs ⇒ App ⇒ Bundle ID ⇒ Push Notifications Edit에서 CertificateSigningRequest을 등록해준다 (https://developer.apple.com/account/resources/identifiers/list)

🔥 5. Xcode에서 GoogleService-Info.plist 등록하기

IOS 루트 경로에 GoogleService-Info.plist을 등록

참조

[React Native FirebaseReact Native Firebase](https://rnfirebase.io/)

https://github.com/react-native-push-notification/ios