'UNUserNotificationCenter need to willPresent code

I have an app written in Swift that uses UNUserNotificationCenter and I have it presenting notifications when the app is in the foreground.

What I want to do is update the UI once the notification has been delivered and the app is in the foreground The following presents the notification just fine, but when it is presented, I also want to execute a function called updateUI() as the notification date is in my UI and I want to clear it as soon as the notification appears.

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    completionHandler([.alert,.sound])
}

I don't know how to add the call to updateUI() in the completion handler.



Solution 1:[1]

You can POST new notification from you AppDelegate and add Observer inside your controller file to change in UI.

@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
    UIApplication.shared.applicationIconBadgeNumber = 0
    NotificationCenter.default.post(name: NSNotification.Name(rawValue: "NewNotification") , object: nil, userInfo: response.notification.request.content.userInfo)
}

@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    completionHandler(.alert)
}

Add Notification Observer in your controller file :

NotificationCenter.default.addObserver(self, selector: #selector(pushNotificationHandler(_:)) , name: NSNotification.Name(rawValue: "NewNotification"), object: nil)

then call UI update method :

func pushNotificationHandler(_ notification : NSNotification) {
    self.updateUI()
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 CÅ“ur