UNUserNotificationCenter 需要将当前代码

Ste*_*nch 2 xcode ios swift usernotifications unusernotificationcenter

我有一个用 Swift 编写的应用程序,它使用 UNUserNotificationCenter,当应用程序处于前台时,我让它显示通知。

我想要做的是在发送通知并且应用程序处于前台后更新 UI 下面显示的通知很好,但是当它显示时,我还想执行一个名为 updateUI() 的函数作为通知日期在我的用户界面中,我想在通知出现后立即清除它。

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

我不知道如何在完成处理程序中添加对 udateUI() 的调用。任何人都可以提供帮助吗?

Sid*_*tre 5

您可以POST从您那里获得新通知,AppDelegate并在您的控制器文件中添加观察者以在 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)
}
Run Code Online (Sandbox Code Playgroud)

在您的控制器文件中添加通知观察者:

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

然后调用 UI 更新方法:

 func pushNotificationHandler(_ notification : NSNotification) {
    self.udateUI()
}
Run Code Online (Sandbox Code Playgroud)