WatchKit 在应用程序不活动时执行任务

WatchKit perform task when app inactive

我正在为 Apple Watch 创建一个独立的应用程序,每 3000 万测量一次心跳率并将它们发送到服务器。 我指的是 this 提取心跳率的项目。该项目包含一个 class,它通过 HealthKit 提取此度量。

我需要做的是使这个任务 运行 永久化,即使该应用程序处于非活动状态。并能够通过我的应用程序中的设置视图禁用它。

所以我的问题是:如何在 Apple Watch 应用程序中永久地在后台执行任务?
谢谢。

看看他们在 documentation 中怎么说:

Workout sessions let apps continue to run in the foreground.

因此您的应用可以在应用处于非活动状态时收集心率信息。然后你可以使用workoutSession(_:didChangeToState:fromState:date:)方法,根据日期 属性.

将信息分成30分钟的时间间隔

If your application is suspended, the delegate receives this call after the application resumes. This means you may receive the notification long after the state changed. Check the date parameter to determine when the state change actually occurred.

您终于可以在应用程序激活时向服务器发送信息了。

更新:

您还可以在 workoutSession(_:didChangeToState:fromState:date:) 中调用 openParentApplication:reply: 以在后台向服务器发送统计信息(在 iphone 上)。