swiftswiftuiunusernotificationcenter

How to decrease badge number in iOS 17, applicationIconBadgeNumber was deprecated?


I want to decrease my badge number by one when a user taps a button. The badge number could be 4 for instance so I don't want it to be reset to zero directly.

I wanted to use this code but it was deprecated in iOS 17:

UIApplication.shared.applicationIconBadgeNumber += 1

Instead I need to use below but I can't figure out how to decrease by one instead of setting a whole new value

        let center = UNUserNotificationCenter.current()
    
    do {
        
        try await center.setBadgeCount(0)
        
    } catch {
        
    }

Solution

  • You can set a variable to keep track of the badge count. Call setBadgeCount each time your value changes. You can add more logic and error handling in the button's action closure.

    import SwiftUI
    import UserNotifications
    
    struct ContentView: View {
        @State var badgeCount: Int = 4
        let center = UNUserNotificationCenter.current()
    
        var body: some View {
            VStack {
                Button(action: {
                    badgeCount -= 1
                    center.setBadgeCount(badgeCount)
                    // add your own business logic
                }) {
                    Text("Decrement Badge")
                }
                .task {
                    try? await center.requestAuthorization(options: .badge)
                    try? await center.setBadgeCount(badgeCount)
                }
            }
        }
    }