如果希望在应用程序中使用HealthKit,首先需要在生成证书的时候勾选HealthKit选项。
考虑到目前HealthKit仅仅可以在iPhone设备上使用,不能在iPad或者iPod中使用,所以在接入HealthKit代码之前最好检验下可用性:
if(NSClassFromString(@"HKHealthStore") && [HKHealthStore isHealthDataAvailable]) { // Add your HealthKit code here }
由于HealthKit存储了大量的用户敏感信息,App如果需要访问HealthKit中的数据,首先需要请求用户权限。权限分为读取与读写权限(苹果将读写权限称为share)。请求权限还是比较简单的,可以直接使用 requestAuthorizationToShareTypes: readTypes: completion:
方法。
HKHealthStore *healthStore = [[HKHealthStore alloc] init]; // Share body mass, height and body mass index NSSet *shareObjectTypes = [NSSet setWithObjects: [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierBodyMass], [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierHeight], [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierBodyMassIndex], nil]; // Read date of birth, biological sex and step count NSSet *readObjectTypes = [NSSet setWithObjects: [HKObjectType characteristicTypeForIdentifier:HKCharacteristicTypeIdentifierDateOfBirth], [HKObjectType characteristicTypeForIdentifier:HKCharacteristicTypeIdentifierBiologicalSex], [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount], nil]; // Request access [healthStore requestAuthorizationToShareTypes:shareObjectTypes readTypes:readObjectTypes completion:^(BOOL success, NSError *error) { if(success == YES) { // ... } else { // Determine if it was an error or if the // user just canceld the authorization request } }];
如上代码会调用下图这样的权限请求界面:
用户在该界面上可以选择接受或者拒绝某些对于读写健康数据的请求。在确定或者关闭请求界面之后,回调会被自动调用。
从Health Store中读写数据的方法比较直接,HKHealthStore类是提供了很多便捷的方法读取基本的属性。不过如果需要以更多复杂的方式进行查询,可以使用相关的子类:HKQuery。
NSError *error; HKBiologicalSexObject *bioSex = [healthStore biologicalSexWithError:&error]; switch (bioSex.biologicalSex) { case HKBiologicalSexNotSet: // undefined break; case HKBiologicalSexFemale: // ... break; case HKBiologicalSexMale: // ... break; }
// Some weight in gram double weightInGram = 83400.f; // Create an instance of HKQuantityType and // HKQuantity to specify the data type and value // you want to update NSDate *now = [NSDate date]; HKQuantityType *hkQuantityType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierBodyMass]; HKQuantity *hkQuantity = [HKQuantity quantityWithUnit:[HKUnit gramUnit] doubleValue:weightInGram]; // Create the concrete sample HKQuantitySample *weightSample = [HKQuantitySample quantitySampleWithType:hkQuantityType quantity:hkQuantity startDate:now endDate:now]; // Update the weight in the health store [healthStore saveObject:weightSample withCompletion:^(BOOL success, NSError *error) { // .. }];
// Set your start and end date for your query of interest NSDate *startDate, *endDate; // Use the sample type for step count HKSampleType *sampleType = [HKSampleType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount]; // Create a predicate to set start/end date bounds of the query NSPredicate *predicate = [HKQuery predicateForSamplesWithStartDate:startDate endDate:endDate options:HKQueryOptionStrictStartDate]; // Create a sort descriptor for sorting by start date NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:HKSampleSortIdentifierStartDate ascending:YES]; HKSampleQuery *sampleQuery = [[HKSampleQuery alloc] initWithSampleType:sampleType predicate:predicate limit:HKObjectQueryNoLimit sortDescriptors:@[sortDescriptor] resultsHandler:^(HKSampleQuery *query, NSArray *results, NSError *error) { if(!error && results) { for(HKQuantitySample *samples in results) { // your code here } } }]; // Execute the query [healthStore executeQuery:sampleQuery];