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

huangapple go评论76阅读模式
英文:

How to enable foreground notification for only some UIViewControllers?

问题

我想在仅选定的UIViewControllers中前台显示通知。

但是,当我设置NotificationCenter以在前台接收特定UIViewController的通知时,Swift会将其应用于全局范围。在某些屏幕上,我不希望看到通知在前台出现,因此我必须在每个屏幕中指定是否在前台显示通知,这通常会导致大量未经管理的代码。

英文:

I want to show notification in foreground for only some selected UIViewControllers.

But When I set NotificationCenter to receive notification in foreground for specific UIViewController then Swift do it for global scope. In some screen I don't want to see notification to appear in foreground and for that I have to specify in every screen to show notification in foreground or not which leads to lot of code usually unmanaged.

答案1

得分: 4

你可以将条件放在通知委托方法中,以决定是否为特定视图控制器显示通知。

@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) { 

        // 为 FirstViewController 和 SecondViewController 显示通知
        completionHandler([.alert, .badge, .sound])
    }
    else {
       // 当你不想显示通知时执行其他操作
    }
}

希望对你有帮助。

英文:

You can put the condition in the notification delegate method to show notification for a specific view controller or not.

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

I hope this will be helpful to you...

huangapple
  • 本文由 发表于 2020年1月6日 19:51:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/59611619.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定