본문 바로가기
Flutter

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

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

 

2024.10.23 - [안드로이드] - [Android Studio] Firebase FCM 사용법 . Part. 2

 

[Android Studio] Firebase FCM 사용법 . Part. 2

1. Android Studio 코드 추가  1-1. MainActivity override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) FirebaseApp.initializeApp(this@MainActivity) firebaseToken()} private fun f

jangstory.tistory.com

 

 

IOS 에서 Firebase fcm 을 포그라운드, 백그라운드 사용하는 방법을 포스팅 했지만 한 가지 문제가 더 있습니다. 

바로 App이 완전히 죽은 상태에서는 동작을 하지 못하는 것 입니다. 

 

Firebase의 onBackgroundMessage 는 IOS 에서 지원을 해주지 않기 때문 입니다.

여러가지 방법을 시도 해봤지만 제가 사용한 방법은 NotificationService 를 사용하는 법 이었습니다.

 

1. Notification Service란?

iOS에서는 **알림(Notification)**을 관리하고 제공하기 위해 여러 가지 Notification Service를 지원합니다. Apple이 제공하는 **APNs (Apple Push Notification Service)**가 가장 핵심적인 서비스이며, 앱이 실행 중이거나 백그라운드 상태일 때도 푸시 알림을 받을 수 있도록 설계되어 있습니다.

APNs (Apple Push Notification Service)

  • Apple이 제공하는 공식 푸시 알림 서비스
  • 앱이 실행 중이 아니더라도 서버에서 알림을 보내 수신 가능
  • **Firebase Cloud Messaging(FCM)**도 APNs를 통해 iOS 기기에 알림을 전달함
  • 앱이 백그라운드 또는 종료 상태일 때도 푸시 알림을 받을 수 있음

 

 

 

2. NotificationService 사용하는 법

1. Xcode에서 Extension 추가

  1. Xcode에서 Runner.xcworkspace 파일을 엽니다.
  2. File > New > Target을 선택합니다.
  3. Notification Service Extension을 검색하고 선택합니다.
  4. Product Name을 NotificationService(자신이 설정하고 싶은 이름)로 설정하고 완료합니다.
  5. Activate를 눌러 활성화합니다.

 

Xcode 노티피케이션 이미지

 

 

 

2.  ios - Notification 폴더 생성 확인 

import UserNotifications

class NotificationService: UNNotificationServiceExtension {

    var contentHandler: ((UNNotificationContent) -> Void)?
    var bestAttemptContent: UNMutableNotificationContent?

    override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
        self.contentHandler = contentHandler
        bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
        
        if let bestAttemptContent = bestAttemptContent {
            // Modify the notification content here...
            bestAttemptContent.title = "\(bestAttemptContent.title) [modified]"
            
            contentHandler(bestAttemptContent)
        }
    }
    
    override func serviceExtensionTimeWillExpire() {
        // Called just before the extension will be terminated by the system.
        // Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used.
        if let contentHandler = contentHandler, let bestAttemptContent =  bestAttemptContent {
            contentHandler(bestAttemptContent)
        }
    }

}

 

 

3. ios - Notification - Info.plist 확인 

<key>NSExtension</key>
<dict>
    <key>NSExtensionPointIdentifier</key>
    <string>com.apple.usernotifications.service</string>
    <key>NSExtensionPrincipalClass</key>
    <string>$(PRODUCT_MODULE_NAME).NotificationService</string>
</dict>

 

 

이렇게 설정을 하면 앱이 완전히 꺼졌을 때에도 메세지가 오게끔 설정 할 수 있다. 

 

주의사항 

  • Xcode에서 Runner 프로젝트를 선택한 후, NotificationService의 Deployment Target을 iOS 13.0 이상으로 설정합니다.
  • PostMan 으로 테스트 시 content-available : 1 을 넣어줘야합니다 . (아래 예시)
{
  "message": {
    "token": "esCVwbhIx0eEqAjVaqO0l0:APA91bFKzlnMJ13s......", 
    "notification": {
      "title": "새로운 알림",
      "body": "알림 내용입니다."
    },
    "data" : {
      "title": "새로운 알림",
      "body": "알림 내용입니다."
    },
    "apns": {
      "payload": {
        "aps": {
          "content-available" : 1, 
          "mutable-content": 1,
          "sound": "default"
        }
      }
    }
  }
}

 

 

마무리

다음에는 Flutter Ios 에서 shared preferences 를 사용할 수 있도록 설정하는 방법을 포스팅 하겠습니다.

반응형