ios - 获取当前用户屏幕显示或不显示远程通知警报

标签 ios swift push-notification apple-push-notifications

我正在我的应用程序中实现远程通知:

当应用程序位于前台时,我使用

控制远程通知的行为
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification, withCompletionHandler
completionHandler: @escaping (UNNotificationPresentationOptions) ->
Void)

我正在为完成处理程序使用这 3 个不同的选项:

completionHandler([.alert, .sound])
completionHandler([.sound])

例如,我的应用程序中有 2 个屏幕:

  • 首页
  • 对话列表

当用户使用我的应用程序并收到对话更新的远程通知时,我想要:

  • 如果他在主屏幕上 ->completionHandler([.alert, .sound])
  • 如果他在对话屏幕列表中 ->completionHandler([.sound])

我的应用程序有许多不同的屏幕,可以触发不同类型的远程通知。 获取当前查看的屏幕并选择所需的完成处理程序的最佳方法是什么。

最佳答案

一个简单的方法是检查当前的可见 Controller (顶 View Controller )。寻找最上面的代码是:

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
}

可以从应用程序中的任何位置调用它。

关于ios - 获取当前用户屏幕显示或不显示远程通知警报,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49893076/

相关文章:

ios - 分享视频到 Facebook - Swift IOS

ios - 我无法在 TableView 内加载 TableView 单元格

ios - 以编程方式加载自定义字体时出现内存问题

swift - 通过键盘扩展在 UINavigationController 中呈现 subview

ios - 在 Swift 中通过 TouchID 生成哈希或字符串

android - 当我的移动应用程序向我的服务器报告它们的设备 token 时,我应该如何处理身份验证?

ios - Azure 移动服务 - 推送通知注册不起作用 [ios]

android - 当我的 Android 应用程序处于前台时,我想隐藏其他应用程序的所有通知。这可能吗?如何?

ios - 如何将 ImageSlideshow 库与 sdwebimage 库一起使用

php - 从我们的服务器发送推送通知时的关键结果