屏幕刚刚关闭后,如何从活动应用程序触发 Apple Watch 触觉反馈(或通知)?

How to trigger an Apple Watch haptic feedback (or notification) from an active app after the screen just turns off?

我正在为 Apple Watch 开发一个独立的倒计时应用程序。计时结束时,手表响铃或振动。

在三种不同的情况下可能会发生这种情况:

  1. 应用程序屏幕在用户的手腕上处于活动状态这是最简单的部分;当计时器结束时,应用程序会运行 sound/haptic 反馈,后台不需要任何东西 运行。 没问题。
  2. 该应用程序在后台使用通知似乎是显而易见的选择,而且它已经运行良好。
  3. 应用程序 在前台,但屏幕关闭 要么是因为它达到了最大唤醒持续时间(15 或 70 秒),要么是因为用户将手腕向后旋转休息位置,自动关闭 Apple Watch 的屏幕。

第三种也是最后一种情况让我感到困惑。第一种和第二种情况在这里都不起作用:当应用程序处于活动状态但屏幕关闭时,应用程序停止 运行,但仍未触发通知,因为应用程序在技术上不在背景.

有什么简单的方法可以解决这个问题吗?

使用Extended Runtime Sessions创建smart alarms

像这样:

func notifyUser(hapticType type: WKHapticType, 
  repeatHandler: ((UnsafeMutablePointer<WKHapticType>) -> Time
Interval)? = nil)

Apple Documentation

For schedulable sessions such as smart alarms, call this method during the session to alert the user. When you call the method, the system plays repeating haptic feedback. If the app isn’t active, the system also displays a system alarm alert on the watch.

The haptic feedback repeats at the interval specified by the repeatHandler, and continues to repeat until the application or system alert invalidates the session.

If the app isn’t active, the user can tap the Stop button to invalidate the session or tap the Open button to activate the app.

If the app is active, the app must invalidate the session by calling its invalidate method.

Only call this method on a schedulable session that’s running: you must schedule the session using the startAtDate: method, and the session’s state must equal WKExtendedRuntimeSessionStateRunning. During a smart alarm session, your app must call this method before the session expires.

你也应该看看the life cycle of watchOS app