iosswiftunusernotificationcenter

How to Update App Badge with Local Notification


I used local notification to deliver a message to the user at the same time I want to update App badge when the notification triggers, but the local notification delegate have functions that deal with notifications when the app is in the foreground and when the user interacts with notification (like a tap on it). Is there any way to update the app badge when the notification triggers and the app is in background?

Handle notification when the app is in the foreground

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

Handle notification when the tap action on it

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

Solution

  • To update App badge when local notification trigger set the badge value in the code bellow when set the notification:

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