【问题标题】:How to enable foreground notification for only some UIViewControllers?如何仅为某些 UIViewControllers 启用前台通知?
【发布时间】:2020-01-06 11:51:11
【问题描述】:

我只想在前台显示一些选定的 UIViewControllers 的通知。

但是当我将 NotificationCenter 设置为在前台接收特定 UIViewController 的通知时,Swift 会在全局范围内执行此操作。在某些屏幕中,我不想看到通知出现在前台,为此我必须在每个屏幕中指定是否在前台显示通知,这会导致很多代码通常不受管理。

【问题讨论】:

    标签: ios swift push-notification nsnotificationcenter swift5


    【解决方案1】:

    您可以将条件放在通知委托方法中,以显示或不显示特定视图控制器的通知。

    @available(iOS 10.0, *)
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    
        let navigationController: UINavigationController = self.window?.rootViewController as! UINavigationController
    
        if (navigationController.topViewController is FirstViewController) || (navigationController.topViewController is SecondViewController) { 
    
            //Show notification for First and Second ViewController 
            completionHandler([.alert, .badge, .sound])
        }
        else {
           //Do whatever when you don't want to show notification
        }
    }
    

    希望对你有帮助……

    【讨论】:

    • 这是为特定 UIViewControllers 做的好方法
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多