FCM Push Notification P8 키 발급 과정

김태호·2022년 5월 3일
0

iOS-fcm

목록 보기
2/2

FCM 발급 과정 묘사

다음 과정을 원활하게 진행하기 위해서는 Apple의 개발자로 등록되어 있어야 한다.
2021.12.01 기준 작업

Step 1 - P8 Key 발급

Certificates, Identifiers & Profiles > Keys > 클라우드 메시징 탭으로 이동


다음과 같이 Key Name 을 입력하고 APNs 를 활성화 하여 continue를 눌러 키를 발급한다.

다운로드한 파일은 다음과 같은 형식으로 저장됩니다.

AuthKey_{KEY_ID}.p8

KEY_ID 는 중요한 값이니 변경하지 않도록 합니다.

Step 2 - TEAM ID & App 정보 확인하기

TEAM ID


다음 과정중 하나를 선택

  1. Account > Membership 에서 확인
  2. 로그인 페이지에서 우측 상단에서 확인

App 정보


FCM 을 이용하고자 하는 App 프로젝트에서 Bundle Identifier 를 확인한다.

Xcode > myApp.xcodeproj > myApp > General > Bundle Identifier

Step 3 - App IDs 생성

Certificates, Identifiers & Profiles > App IDs 탭으로 이동

설정 순서

  1. Register a new identifier : App IDs
  2. Select a type: App
  3. Description: My App Description
  4. Bundle ID: com.myApp.m (Explicit)
  5. Register 완료

Step 4 - FCM 계정에 com.myApp.m 프로젝트를 등록 및 설정

Google 의 FCM 가이드 링크 이다.

가이드를 따라서 Xcode 를 설정한 다음 iOS 프로젝트의 APNs 설정을 위해 Apple 앱 구성에 P8 인증키를 입력한다.

위의 과정에서 발급 받은 것이 P8 인증키 이면 APN 인증키에 등록하고, P12 인증서이면 APN 인증서에 등록해야한다.

Step 5 - Xcode에서 Push Notification 설정 추가와 Developer 계정의 App ID Configuration 확인하기

Xcode > myApp.xcodeproj

Certificates, Identifiers & Profiles > Identifier 에서 다음을 확인

Step 6 - 선택사항

해당 프로젝트는 SwiftUI 프레임워크를 사용중이기 때문에 FCM 에서 권장하는 AppDelegate class 가 없다.
따라서 다음의 코드를 myApp.swift (앱의 진입점이 되는 파일) 에 다음 코드를 넣어 수정한다.

struct MyApp: App {
    @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
    
    var body: some Scene {
        WindowGroup {
            NavigationView {
                IntroScene()
                    .navigationBarHidden(true)
            }
        }
    }
}

class AppDelegate: NSObject, UIApplicationDelegate {
    // App이 실행될때 실행되는 매서드
    func application(_ application: UIApplication,
                     didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool {
        
        FirebaseApp.configure()
        
        //원격 알림 등록
        if #available(iOS 10.0, *) {
            // For iOS 10 display notification (sent via APNS)
            UNUserNotificationCenter.current().delegate = self
            
            let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
            UNUserNotificationCenter.current().requestAuthorization(
                options: authOptions,
                completionHandler: { _, _ in }
            )
        } else {
            let settings: UIUserNotificationSettings =
            UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
            application.registerUserNotificationSettings(settings)
        }
        
        application.registerForRemoteNotifications()
        
        // Messaging
        Messaging.messaging().delegate = self

        // PUSH foreground
        UNUserNotificationCenter.current().delegate = self
        
        return true
    }
    
    // Firebase Messaging 과 APNs 토큰과 연결
    func application(_ application: UIApplication,
                     didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        Messaging.messaging().apnsToken = deviceToken
    }
}

extension AppDelegate: MessagingDelegate {

    func messaging(_ messaging: Messaging,
                   didReceiveRegistrationToken fcmToken: String?) {
        log.info("FCM Token from the Server ")
        log.info("Registration Token Info: \(String(describing: fcmToken))")
    }
}

extension AppDelegate: UNUserNotificationCenterDelegate {
    func userNotificationCenter(_ center: UNUserNotificationCenter,
                                willPresent notification: UNNotification,
                                withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        let userInfo = notification.request.content.userInfo
        log.info("Will Present User INFO : \(userInfo)")
        completionHandler([.banner, .sound, .badge])
    }
    
    // 푸시 메시지를 받았을때
    func userNotificationCenter(_ center: UNUserNotificationCenter,
                                didReceive response: UNNotificationResponse,
                                withCompletionHandler completionHandler: @escaping () -> Void) {
        let userInfo = response.notification.request.content.userInfo
        log.info("Did Receieve User INFO : \(userInfo)")
        completionHandler()
    }
}
profile
신입 모바일 개발자 입니다!

0개의 댓글