如何在 iOS 17 中减少徽章数量,applicationIconBadgeNumber 已被弃用?

问题描述 投票:0回答:1

我想在用户点击按钮时将我的徽章数量减一。例如,徽章编号可以是 4,所以我不希望它直接重置为零。

我想使用这段代码,但它在 iOS 17 中已被弃用:

UIApplication.shared.applicationIconBadgeNumber += 1

相反,我需要使用下面的内容,但我不知道如何减少一而不是设置一个全新的值

        let center = UNUserNotificationCenter.current()
    
    do {
        
        try await center.setBadgeCount(0)
        
    } catch {
        
    }
swift swiftui unusernotificationcenter
1个回答
0
投票

您可以设置一个变量来跟踪徽章计数。每次您的值发生变化时,调用“setBadgeCount()”。您可以在按钮主体中添加更多逻辑和错误处理。

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)
            }
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.