如何使用本地通知更新 App Badge

How to Update App Badge with Local Notification

我使用本地通知向用户发送消息,同时我想在通知触发时更新应用徽章,但是本地通知委托具有处理应用程序在前台时通知的功能,并且当用户与通知交互时(比如点击它)。当通知触发且应用程序处于后台时,有什么方法可以更新应用程序徽章吗?

当应用程序在前台时处理通知

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    // run code when app in foreground
    
}

处理点击操作时的通知

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
    // run code when user interact with notification only
}

要在本地通知触发时更新应用徽章,请在设置通知时在以下代码中设置徽章值:

func schedulNotification() {
let content = UNMutableNotificationContent()
content.badge = 1  // That will appear on app icon when notification trigger
// Continue notification settings...
}