Save/Delete 到 HealthKit With WatchKit 和 Widget(今天的扩展)?

Save/Delete to HealthKit With WatchKit and Widget (Today Extension)?

这是一个我知道有答案的问题,因为我看到了执行此功能的应用程序。我试过(直接写,使用后台获取)但没有任何效果。我在应用程序商店中找到了一个应用程序,它具有我正在寻找的功能。后台获取设置为关闭且主应用程序不在后台 运行。我转到小部件并添加一个项目。我打开 HealthKit,我看到了预期的数据。

我想为我的应用程序做同样的事情。我希望今天的扩展(小部件)and/or WatchKit 扩展能够写入 HealthKit 商店,即使应用程序不在后台 运行。 就像我说的那样,我已经测试了一个可以执行此功能的应用程序,即使在 Apple 文档中它是这样说的:

The HealthKit store can only be accessed by an authorized app. You cannot access HealthKit from extensions (like the Today view) or from a WatchKit app.

Because the HealthKit store is encrypted, your app cannot read data from the store when the phone is locked. This means your app may not be able to access the store when it is launched in the background. However, apps can still write data to the store, even when the phone is locked. The store temporarily caches the data and saves it to the encrypted store as soon as the phone is unlocked.

如有任何答案或见解,我们将不胜感激。谢谢大家

在设备锁定时,Health Data Store 确实已加密。锁定被定义为需要在设备上输入密码并且屏幕已关闭(因此在返回主屏幕之前需要输入密码或触摸 ID)。虽然商店已加密,但无法从中读取任何数据,无论该应用程序是否 运行 在后台运行。即使在应用程序 运行 时设置观察者查询也不允许它继续被读取。我想这种保护级别只需使用带有 NSFileProtectionComplete 选项的数据保护功能即可完成。

您在另一个应用程序中观察到了哪些 HealthKit 功能?如果它显示的是步数和距离数据,那么他们很可能直接从计步器 (CMPedometer) 获取这些数据,这在设备锁定时不受限制。

Lehn0058 关于授权的评论是正确的。我必须从 WatchKit 和 Today Extension 明确请求授权,即使授权已经在应用程序中给出。之后,两者都可以写入 Health Store。上面 Apple 的评论只与从 Health Store 读取而不是写入 Health Store 有关。以下是一些遇到相同问题的其他人的示例代码。再次感谢。

在 WatchKit 中 InterfaceController.m

- (void)awakeWithContext:(id)context {
    [super awakeWithContext:context];
    // Configure interface objects here.
    [[HealthKitManager sharedManager] requestHealthKitAccess];
}

在今日扩展中TodayViewController.m

- (void)viewDidLoad {
    [super viewDidLoad];    
    [[HealthKitManager sharedManager] requestHealthKitAccess];
}