Norway


Calculate the new before sending the notification :

content.badge =  NSNumber(integerLiteral: UIApplication.shared.applicationIconBadgeNumber + 1)

And send the local notifications like so:

let appBadge = UIApplication.shared.applicationIconBadgeNumber
let center = UNUserNotificationCenter.current()
center.getPendingNotificationRequests(completionHandler: { pendingNotificationRequests in
    let content = UNMutableNotificationContent()
    content.title = "Meeting Reminder"
    content.subtitle = "Let's go"
    content.body = "Don't forget to bring coffee."
    content.badge =  NSNumber(integerLiteral: appBadge + pendingNotificationRequests.count + 1)
    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5,
                                                    repeats: false)

    let requestIdentifier = UUID().uuidString  //You probably want to  these request identifiers if you want to remove the corresponding notifications later
    let request = UNNotificationRequest(identifier: requestIdentifier,
                                        content: content, trigger: trigger)

    center.add(request, withCompletionHandler: { (error) in
        // Handle error
    })
})

And to handle interacting with the notification, update the badge of the , and the badge of the upcoming notifications:

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
    UIApplication.shared.applicationIconBadgeNumber -= 1

    let center = UNUserNotificationCenter.current()
    center.getPendingNotificationRequests(completionHandler: {requests in
        let newRequests: [UNNotificationRequest] = requests.map { request in
            let newContent: UNMutableNotificationContent = request.content as! UNMutableNotificationContent
            newContent.badge = (Int(truncating: request.content.badge ?? 0) - 1) as NSNumber
            let newRequest: UNNotificationRequest =  UNNotificationRequest(identifier: request.identifier,
                                                   content: newContent,
                                                   trigger: request.trigger)
            return newRequest
        }
        newRequests.forEach { center.add($0, withCompletionHandler: { (error) in
                // Handle error
            })
        }
    })
    completionHandler()
}



Source link

LEAVE A REPLY

Please enter your comment!
Please enter your name here