UNUserNotificationCenter 需要将Present code
Posted
技术标签:
【中文标题】UNUserNotificationCenter 需要将Present code【英文标题】:UNUserNotificationCenter need to willPresent code 【发布时间】:2018-02-20 00:35:16 【问题描述】:我有一个用 Swift 编写的应用程序,它使用 UNUserNotificationCenter,当应用程序在前台时,我让它显示通知。
我想要做的是在发送通知并且应用程序处于前台后更新 UI 以下显示通知很好,但是当它出现时,我还想执行一个名为 updateUI() 的函数因为通知日期在我的 UI 中,我想在通知出现后立即清除它。
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)
completionHandler([.alert,.sound])
我不知道如何在完成处理程序中添加对 udateUI() 的调用。 有人可以帮忙吗?
【问题讨论】:
您可以将通知发布到您的视图控制器。 【参考方案1】:您可以POST
来自您AppDelegate
的新通知,并在您的控制器文件中添加 Observer 以更改 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)
在你的控制器文件中添加通知观察者:
NotificationCenter.default.addObserver(self, selector: #selector(pushNotificationHandler(_:)) , name: NSNotification.Name(rawValue: "NewNotification"), object: nil)
然后调用 UI 更新方法:
func pushNotificationHandler(_ notification : NSNotification)
self.udateUI()
【讨论】:
非常感谢。像魅力一样工作。以上是关于UNUserNotificationCenter 需要将Present code的主要内容,如果未能解决你的问题,请参考以下文章
UNUserNotificationCenter.current().getDeliveredNotifications 只返回一个空数组
我如何知道 UNUserNotificationCenter 的 removeAllPendingNotificationRequests() 何时完成?
UNUserNotificationCenter 需要将Present code
使用 UNUserNotificationCenter 后没有调用 didReceiveLocalNotification