【问题标题】:Handling push notifications while watchOS app is in the foreground?在 watchOS 应用程序处于前台时处理推送通知?
【发布时间】:2017-10-31 12:47:56
【问题描述】:

我正在构建 iOS + watchOS 应用程序,这些应用程序需要在 iOS 和 watch 应用程序状态的所有可能组合中通知用户更新信息:当 iOS 和 watchOS 都在前台运行时,当它们都在前台运行时背景,以及当其中一个或另一个在背景中时。

我成功地处理了这四种情况中的三种情况的推送通知。我被卡住的地方是当手表应用程序在前台打开但iOS应用程序在后台时 - 我找不到手表通知控制器、它的 ExtensionDelegate 或 iOS AppDelegate 的任何方法,当一个在这种情况下会推送远程通知。

在 iOS AppDelegate 中,当 iOS 应用处于前台且手表应用处于任一状态时推送通知时会触发此事件:

func userNotificationCenter(_ center: UNUserNotificationCenter,
                            willPresent notification: UNNotification,
                            withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)

在 WatchKit Extension NotificationController 中,当 iOS 和手表应用都在后台时推送通知时会触发此事件:

override func didReceive(_ notification: UNNotification, withCompletion completionHandler: @escaping (WKUserNotificationInterfaceType) -> Swift.Void) { ... }

然而,如果在推送通知时手表应用在前台,而 iOS 应用在后台,则通知横幅会出现在 iPhone 上(即使屏幕被锁定),并且我没有办法处理它并更新手表,除非手表当时也在后台。

有什么想法吗?

【问题讨论】:

    标签: ios swift apple-push-notifications watchos watchos-3


    【解决方案1】:

    想通了。要在手表应用程序处于后台和前台时处理通知,您似乎必须在 NotificationController 中的 didReceive 方法(用于后台通知)和 ExtensionDelegate 中的 UNUserNotificationDelegate 协议中使用 willPresent 方法(对于前台通知):

    func userNotificationCenter(_: UNUserNotificationCenter, willPresent: UNNotification, withCompletionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        print("willPresent fired from watch delegate")
    }
    

    让我感到困惑的是文档说:

    用户通知框架为 iOS、watchOS 和 tvOS 应用程序提供了一个统一的 API,并支持与本地和远程通知相关的大多数任务。以下是您可以使用此框架执行的一些任务示例...

    但是,虽然他们为 iOS、tvOS 和 macOS 执行此操作,但文档并未具体说明如何为手表执行此操作。

    在 Watch ExtensionDelegate 中不需要完成注册和设备令牌步骤(实际上是不可能的,因为您需要 UIApplication 模块来执行此操作),但有必要调用:

    UNUserNotificationCenter.current().delegate = self
    

    在启动 ExtensionDelegate 时。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-07-04
      • 2017-06-26
      • 1970-01-01
      • 2018-08-04
      • 2023-03-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多