project/Kuring(공지알림)

[iOS] FCM(Firebase Cloud Message) 정리 및 테스트 환경

lgvv 2021. 12. 17. 15:32

[iOS] FCM(Firebase Cloud Message) 정리 기본



과거에는 시뮬레이터에서 동작하지 않았으나, 이제는 시뮬레이터에서 테스트 가능

 

 

목차

1. AppDelegate.swift 

2. Xcode -> Targets 설정하기

3. APNs 설정하기

4. Firebase console

 



AppDelegate.swift

AppDelegate에 메시지 Delegate 설정해주기

 

import UIKit
import Firebase
import UserNotifications

@main
class AppDelegate: UIResponder, UIApplicationDelegate {
    
    
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        
        FirebaseApp.configure()
        UNUserNotificationCenter.current().delegate = self
        Messaging.messaging().delegate = self
        
        let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
        UNUserNotificationCenter
            .current()
            .requestAuthorization(
                options: authOptions,completionHandler: { (_, _) in }
            )
        application.registerForRemoteNotifications()
        
        return true
    }
    
    // MARK: UISceneSession Lifecycle
    
    func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
    
        return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
    }
    
    func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {}
    
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})

        Messaging.messaging().apnsToken = deviceToken
    }
    
    
}

extension AppDelegate : MessagingDelegate {
    func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
        print("파이어베이스 토큰: \(String(describing: fcmToken))")
    }
}

extension AppDelegate : UNUserNotificationCenterDelegate {
    func userNotificationCenter(_ center: UNUserNotificationCenter,willPresent notification: UNNotification,withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        completionHandler([.banner, .list, .badge, .sound])
    }
    
    func userNotificationCenter(_ center: UNUserNotificationCenter,didReceive response: UNNotificationResponse,withCompletionHandler completionHandler: @escaping () -> Void) {
        completionHandler()
    }
}

 

AppDelegate를 구성하는 가장 기본적인 부분

 

 

Xcode -> Targets 설정하기

 

설정 변경

 

 

APNs 설정

애플 개발자 사이트에서 권한이 있어야 함.

 

https://developer.apple.com/account/#!/welcome

 

로그인 - Apple

 

idmsa.apple.com

 

이거 누르기
Keys에서 키를 생성, APN 추가
Key ID 기억하기

 


생성하고 난 후 Done을 누르기 전에 .p8 파일을 다운하기

처음에 한번만 받은 후 이후에는 받을 수 없음.

 

여기로 이동해서 내 프로젝트의 bundle id로 하나를 만들어 주세요
정상 완료

 

 

Firebase console

 

파이어베이스 콘솔에서 프로젝트 생성
APN 인증키 등록

 

 

해당 과정은 매우 간단하며, 생성하기 누르면 .p8 파일을 드래그해서 올려두고 keys의 key ID를 입력하면 끝

TeamID는 Apple developer Membership에 있음

 

다음으로는 Cloud Message로 이동하고 여기서 토큰을 얻어서 세팅

 

FCM토큰추가
토큰 추가

 

 

(참고)

https://onedaycodeing.tistory.com/92

 

IOS 파이어베이스 Push 메세지 셋팅 ( FCM )

IOS 파이어베이스로 FCM푸시 메세지 셋팅하는 방법을 알아볼게요. 우선 코코아팟이 셋팅이 되어있어야 하기때문에 게시글을 참고해주세요. https://onedaycodeing.tistory.com/88 cocoapods(코코아) 설치 및 라

onedaycodeing.tistory.com