英文:
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...
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论