Ios 获取当前用户屏幕以显示或不显示远程通知警报
我正在我的应用程序中实施远程通知: 当应用程序位于前台时,我控制远程通知的行为Ios 获取当前用户屏幕以显示或不显示远程通知警报,ios,swift,push-notification,apple-push-notifications,Ios,Swift,Push Notification,Apple Push Notifications,我正在我的应用程序中实施远程通知: 当应用程序位于前台时,我控制远程通知的行为 func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) 我正在为
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification, withCompletionHandler
completionHandler: @escaping (UNNotificationPresentationOptions) ->
Void)
我正在为完成处理程序使用这3种不同的选项:
completionHandler([.alert, .sound])
completionHandler([.sound])
例如,我的应用程序中有2个屏幕:
- 家
- 对话列表
- 如果他在主屏幕->completionHandler([.alert,.sound])
- 如果他在对话屏幕->completionHandler([.sound])列表中
获取当前查看的屏幕并选择所需的完成处理程序的最佳方法是什么。一个简单的方法是检查当前可见控制器(俯视控制器)。查找最顶层的代码是:
extension UIApplication {
static func topViewController(controller: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {
if let navigationController = controller as? UINavigationController {
return topViewController(controller: navigationController.visibleViewController)
}
if let tabController = controller as? UITabBarController {
if let selected = tabController.selectedViewController {
return topViewController(controller: selected)
}
}
if let presented = controller?.presentedViewController {
return topViewController(controller: presented)
}
return controller
}
}
然后,在选择何时提交通知或不提交通知时,您可以执行以下操作:
if UIApplication.topViewController() is HomeViewController {
// Top controller is Home
}
这可以从应用程序中的任何点调用。这绝对是我需要的。UIApplication.topViewController()是否为HomeViewController,而UIApplication.topViewController是否为HomeViewController?