SwiftUI프로그래밍

[iOS, SwfitUI] 원격 푸시 알림으로 앱 아이콘의 배지(Badge) 숫자 보일 때 제거 해제 방법

iOS에서 원격 푸시 알림으로 앱 아이콘의 배지(Badge) 숫자가 설정되었는데, SwiftUI 앱에서 앱 실행 시 배지 숫자가 계속 남아있는 경우, 수동으로 배지를 초기화(reset) 해줘야 합니다.


해결 방법: 앱 실행 시 badge 숫자를 0으로 초기화

SwiftUI에서는 ApponAppear 또는 onChange 등을 활용해 앱이 활성화될 때 아래 코드를 실행해주면 됩니다.

import SwiftUI
import UserNotifications

@main
struct MyApp: App {
    @Environment(\.scenePhase) var scenePhase
    
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
        .onChange(of: scenePhase) { newPhase in
            if newPhase == .active {
                // 앱이 포그라운드로 전환되었을 때 배지 숫자 초기화
                UIApplication.shared.applicationIconBadgeNumber = 0
                
                // 알림 센터에 남은 알림 제거 (선택사항)
                UNUserNotificationCenter.current().removeAllDeliveredNotifications()
            }
        }
    }
}

설명

  • UIApplication.shared.applicationIconBadgeNumber = 0
    → 아이콘에 표시되는 배지를 0으로 초기화합니다.
  • UNUserNotificationCenter.current().removeAllDeliveredNotifications()
    → 이미 도착해 사용자에게 표시된 푸시 알림도 제거합니다. (알림 센터에서 지워짐)

추가 팁: 백그라운드에서 복귀 시에도 초기화하고 싶다면?

이미 위의 scenePhase 감지를 통해 .active 상태에서 자동 초기화되므로 충분합니다.

error: Content is protected !!