본문 바로가기
Flutter

[Flutter] Firebase FCM 사용하기 Part. 4-2 (ios)

by 개발_블로그 2025. 2. 3.
반응형

 

1편을 참조하시길 바랍니다. 

https://jangstory.tistory.com/entry/Flutter-Firebase-FCM-%EC%82%AC%EC%9A%A9%ED%95%98%EA%B8%B0-Part-4-ios

 

 

IOS 에서 FirebaseMessaging.onBackgroundMessage 가 동작하지 않는 것은 Apple이 백그라운드에서의 코드 실행을 제한하며, 특히 백그라운드 상태일 때 푸시 알림 처리를 제어한다고 합니다. 

1. 백그라운드를 사용하려면 ios / Runner / AppDelegate.swift 코드를 수정해야합니다.

초기 AppDelegate.swift 코드.

@main
@objc class AppDelegate: FlutterAppDelegate {

    override func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
    ) -> Bool {
        GeneratedPluginRegistrant.register(with: self)
        return super.application(application, didFinishLaunchingWithOptions: launchOptions)
    }

 

2.백그라운드에서 메세지가 왔을 시 코드 수정 

코드를 아래와 같이 수정해주면 백그라운드 상태일 때 메세지가 수신이 됩니다.

// import
import UIKit
import UserNotifications
import Firebase

@main
@objc class AppDelegate: FlutterAppDelegate {

    override func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
    ) -> Bool {
        FirebaseApp.configure() // Firebase 추가
        GeneratedPluginRegistrant.register(with: self)

		// 권한 추가 
        let center = UNUserNotificationCenter.current()
        center.delegate = self
        center.requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
            if let error = error {
                print("Notification permission error: \(error)")
            }
        }

         application.registerForRemoteNotifications()


        return super.application(application, didFinishLaunchingWithOptions: launchOptions)
    }

// 백그라운드 상태일 때 메세지 수신
    override func application(
        _ application: UIApplication,
        didReceiveRemoteNotification userInfo: [AnyHashable: Any],
        fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void
    ) {
     	// 자신이 설정하고 싶은 코드 추가 
        completionHandler(.newData)
    }
}

 

반응형