您好,我正在尝试设置启用后台交付的健康商店观察员。我的问题是当屏幕锁定时它不会提供任何东西。我已经简化了这个问题的代码以达到目的:) 我的 plist 中有 HealthKit,并且我接受了 healthStore 类型的步数。 当应用程序打开且屏幕未锁定时,一切都很好。但是当屏幕被锁定时,我没有得到任何观察结果。 出于测试目的,频率设置为立即。
我的代码如下
- (void)setupHealthStore{
if ([HKHealthStore isHealthDataAvailable])
{
NSSet *readDataTypes = [self dataTypesToRead];
self.healthStore = [[HKHealthStore alloc]init];
[self.healthStore requestAuthorizationToShareTypes:nil readTypes:readDataTypes completion:^(BOOL success, NSError *error)
{
if (success)
{
HKQuantityType *quantityType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
[self.healthStore enableBackgroundDeliveryForType:quantityType frequency:HKUpdateFrequencyImmediate withCompletion:^(BOOL success, NSError *error)
{
if (success)
{
[self setupObserver];
}
}];
}
}];
}
上面的方法在AppDelegate didfinishLaunchWithOptions中调用
下一个方法是
- (void)setupObserver{
HKQuantityType *quantityType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
HKObserverQuery *query = [[HKObserverQuery alloc]initWithSampleType:quantityType predicate:nil updateHandler:^(HKObserverQuery *query, HKObserverQueryCompletionHandler completionHandler, NSError *error)
{
if (!error)
{
[self alarm];
if (completionHandler)
{
NSLog(@"Completed");
completionHandler();
}
}
else
{
if (completionHandler)
{
completionHandler();
}
}
}];
[self.healthStore executeQuery:query];
当我打开应用程序时,它会立即返回观察结果。
最佳答案
当 iPhone 被锁定时,您无法以任何方式访问 healthKit 数据。
当iPhone解锁但应用程序处于后台时,您只能使用HKObserverQuery,用于了解是否添加了一些新样本。
当 iPhone 解锁且应用程序在前台时,您可以使用与 HealthKit 框架相关的所有内容。
关于ios - 屏幕锁定时 HealthStore enableBackgroundDelivery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28458231/