conyang's iOS

[iOS] FCM으로 Push Notification 구현하기 본문

iOS

[iOS] FCM으로 Push Notification 구현하기

conyang 2024. 3. 15. 00:07

 원격 푸시를 구현하기 위해선 개발자 계정 멤버십이 필요합니다. 

1. APNs Key 발급


1. Apple Developer Member Center > Keys에 들어갑니다.

   Keys 옆의 + 버튼을 눌러 키를 생성합니다.

 

2. Key 이름을 작성하고, Apple Push Notifications service (APNs)를 선택합니다.

 

3. Continue > Register를 완료한 다음 Download 버튼을 눌러 p8 파일을 다운로드 합니다.

다운로드한 키 파일은 한 번만 다운로드할 수 있으니, 보관해둬야 합니다.

 

 

2. Firebase 프로젝트 설정


1. Firebase에서 새 프로젝트를 생성합니다.

 

2. iOS 프로젝트를 추가합니다.

 

3.  앱 등록, 구성 파일 다운로드합니다.(안내대로 따라가면 됩니다.)

 

Xcode 프로젝트를 생성할 때는 Firebase에 등록한 Bundle Identifier와 동일한 앱 번들 아이디로 작성해주세요.

 

4. 프로젝트 설정 > 클라우드 메세징 에서  APN 인증 키를 업로드합니다.

 

다운받았던 인증키 파일을 업로드 해줍니다. 키 ID는 p8파일의 키 아이디와 동일하게 입력합니다. 팀 ID는 apple developer에 있는 팀 ID를 입력합니다.

 

 

3. Xcode 프로젝트 설정


1. Xcode Project signing & capabailities 부분에서 + capability를 클릭합니다.

2. Push Notifications와 Background Mode를 추가해줍니다.

 

3. Background Modes에서 Remote Notifications를 체크해줍니다.

 

 

4. Podfile 설정


1. 터미널을 키고 프로젝트 위치에서 pod init을 입력하여 podfile을 생성해줍니다.

 

2. podfile을 열고 Firebase/Messaging을 입력하고 저장합니다.

 

3. pod install을 하여 Firebase Messaging을 프로젝트에 설치합니다.

 

4. Firebase에서 다운받았던 GoogleService-Info.plist를 프로젝트에 추가합니다.

 

 

5. AppDelegate 설정


1. AppDelegate.swift 파일에 다음과 같이 코드를 작성합니다.

import UIKit
import Firebase
import FirebaseMessaging

@main
class AppDelegate: UIResponder, UIApplicationDelegate {

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        
        // 파이어베이스 설정
        FirebaseApp.configure()
        
        // Firebase Messaging 설정
        Messaging.messaging().delegate = self
        
        // 앱 실행 시 사용자에게 알림 허용 권한을 받는다.
        UNUserNotificationCenter.current().delegate = self
        
        let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
        UNUserNotificationCenter.current().requestAuthorization(
            options: authOptions,
            completionHandler: {_, _ in}
        )
        
        // UNUserNotificationCenterDelegate를 구현한 메서드를 실행시킨다.
        application.registerForRemoteNotifications()
        
        return true
    }

    // MARK: UISceneSession Lifecycle

    func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
        // Called when a new scene session is being created.
        // Use this method to select a configuration to create the new scene with.
        return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
    }

    func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
        // Called when the user discards a scene session.
        // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
        // Use this method to release any resources that were specific to the discarded scenes, as they will not return.
    }


}

extension AppDelegate: MessagingDelegate {
    // FCM Token 업데이트 시
    func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
        print("🥳", #function, fcmToken ?? "nil")
    }
    
    // error 발생 시
    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print("😭", error)
    }
}

extension AppDelegate: UNUserNotificationCenterDelegate {
    // 앱 화면을 보고있는 중(포그라운드)에 푸시 올 때
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification) async -> UNNotificationPresentationOptions {
        print("😎", #function)
        
        // 푸시 알림 데이터가 userInfo에 담겨있다.
        let userInfo = notification.request.content.userInfo
        print(userInfo)
        
        if #available(iOS 14.0, *) {
            return [.sound, .banner, .list]
        } else {
            return []
        }
    }
}

 

6. 테스트


1. 앱을 실행시키면 알림을 받을 건지 알림창이 뜹니다.

여기서 허용을 클릭해줍니다.

2. 콘솔에 출력된 토큰을 복사합니다.

 

3. Firebase Project > Messaging 에서 첫 번째 캠페인 만들기를 클릭 > Firebase 알림 메시지 만들기

 

4. 알림 제목과 알림 텍스트를 작성한 후, 테스트 메시지 전송을 클릭합니다.

 

5. 아까 복사해뒀던 fcmToken을 추가한 뒤 테스트를 클릭합니다.

 

6. 테스트를 클릭하면 아래와 같이 푸시 알림이 기기에 뜹니다.