-(void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
if ([HKHealthStore isHealthDataAvailable]){
NSSet *writeDataTypes = [self dataTypesToWrite];
NSSet *readDataTypes = [self dataTypesToRead];
[self.healthStore requestAuthorizationToShareTypes:writeDataTypes readTypes:readDataTypes completion:^(BOOL success, NSError *error) {
NSLog(@"%s",__func__);
if (!success) {
NSLog(@"You didn't allow HealthKit to access these read/write data types. In your app, try to handle this error gracefully when a user decides not to provide access. The error was: %@. If you're using a simulator, try it on a device.", error);
return;
}
dispatch_async(dispatch_get_main_queue(), ^{
// Update the user interface based on the current user's health information.
NSLog(@"=========================== %s",__func__);
});
}];
}
}
requestAuthorizationToShareType 不回调完成方法。
我遇到了类似的问题,权限框没有出现并且没有正确设置HKHealthStore
,事先为我修复了这个问题
self.healthStore = [[HKHealthStore alloc] init];
下面是一个示例实现,它返回类型而不是字符串,如注释部分所述。
-(NSSet*)datatypesToWrite {
NSArray *quantityTypes =
@[HKQuantityTypeIdentifierHeartRate,
HKQuantityTypeIdentifierBodyTemperature,
HKQuantityTypeIdentifierBloodPressureSystolic,
HKQuantityTypeIdentifierBloodPressureDiastolic,
HKQuantityTypeIdentifierRespiratoryRate];
NSMutableArray *hkTypes = [[NSMutableArray alloc] init];
for (NSString *identifier in quantityTypes) {
HKQuantityType *quantType =
[HKObjectType quantityTypeForIdentifier:identifier];
[hkTypes addObject:quantType];
}
// Make sure the types are of the correct style (Quantity, Category, Etc.)
HKCategoryType *catType =
[HKObjectType categoryTypeForIdentifier:HKCategoryTypeIdentifierSleepAnalysis];
[hkTypes addObject:catType];
return [[NSSet alloc] initWithArray:hkTypes];
}
每次首次请求新类型时,都会显示模式权限对话框(但如果重新提示输入未授予的权限,则不会再次显示(。Apple 的指导方针是提示您可能需要的所有内容,但如果我知道有人只要求保存到其中的几种类型中,那么预先请求 12 种类型对我来说有点违反最佳实践。