我的要求是使用enableBackgroundDeliveryForType:方法为背景传递注册任何一个健康数据,如步数,体重,心率等。然后为要检查的相同Health数据创建一个Observer查询。
在这种情况下,如果我的应用程序被用户强行杀死,并使用Health应用程序更改了Health数据。在此阶段是否可以将通知发送到我的应用程序?
是否必须注册任何后台模式,才能通过HKObserverQuery获得健康数据修改通知?
编辑1:
- (void)requestAuthorizationToShareTypes:(NSSet *)typesToShare readTypes:(NSSet *)typesToRead completion:(void (^)(BOOL, NSError *))completion
{
if ([HKHealthStore isHealthDataAvailable]) {
[self.healthStore requestAuthorizationToShareTypes:typesToShare readTypes:typesToRead completion:^(BOOL success, NSError *error) {
if(success)
{
self.authorizationSuccess = YES;
completion(YES, nil);
}
else
{
[MyUtilities showAlertWithTitle:@"Authorization fail!" message:@"You didn't allow to access Health data."];
completion(NO, error);
return;
}
}];
}
else
{
[MyUtilities showAlertWithTitle:@"Sorry!" message:@"Your device does not support Health data."];
NSDictionary *errorDictionary = @{ NSLocalizedDescriptionKey : @"Your device doesn't support Health Kit."};
NSError *error = [[NSError alloc] initWithDomain:@"" code:2 userInfo:errorDictionary];
completion(NO, error);
return;
}
}
- (void)authorizeConsumeHealth:(void (^)(BOOL, NSError *))completion
{
NSSet *readObjectTypes = [NSSet setWithObjects:
[HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierDietaryCaffeine],
[HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierDietaryCalcium],
[HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierDietaryChloride],
[HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierDietaryIron],
[HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount],
[HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierBloodPressureSystolic],
[HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierBloodPressureDiastolic], [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount],
nil];
[self requestAuthorizationToShareTypes:nil readTypes:readObjectTypes completion:^(BOOL success, NSError *error) {
if(completion)
{
completion(success, error);
[self observeStepCountChanges];
}
}];
}
- (void)observeStepCountChanges
{
HKSampleType *sampleType = [HKSampleType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
[self.healthStore enableBackgroundDeliveryForType:sampleType frequency:HKUpdateFrequencyImmediate withCompletion:^(BOOL success, NSError *error) {}];
HKObserverQuery *query = [[HKObserverQuery alloc] initWithSampleType:sampleType predicate:nil updateHandler:^(HKObserverQuery *query, HKObserverQueryCompletionHandler completionHandler, NSError *error) {
if(error)
{
NSLog(@"Steps count observer completion block. Error: %@", error);
}
else
{
NSLog(@"Steps count observer completion block");
}
}];
[self.healthStore executeQuery:query];
}
请帮帮我。感谢。