如何只为某些 UIViewControllers 启用前台通知?

How to enable foreground notification for only some UIViewControllers?

我只想在前台显示某些选定的 UIViewController 的通知。

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

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

@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
    }
}

希望对您有所帮助...