一、配置
在申请App证书的时候 App Services 添加HealthKit服务。
在Xcode项目中 TARGETS -> Capabilities -> HealthKit ON
兼容iOS 10 必须在info.pilst文件中设置
Privacy - Health Update Usage Description value不能为空 否则审核不过
Privacy - Health Share Usage Description value不能为空 否则审核不过
二、代码实例 授权HealthKit:
_healthKitStore = [[HKHealthStorealloc]init];
NSSet *healthKitTypesToRead = [NSSetsetWithArray:@[
[HKObjectTypecharacteristicTypeForIdentifier:HKCharacteristicTypeIdentifierDateOfBirth],
[HKObjectTypecharacteristicTypeForIdentifier:HKCharacteristicTypeIdentifierBloodType],
[HKObjectTypecharacteristicTypeForIdentifier:HKCharacteristicTypeIdentifierBiologicalSex],
[HKObjectTypequantityTypeForIdentifier:HKQuantityTypeIdentifierBodyMass],
[HKObjectTypequantityTypeForIdentifier:HKQuantityTypeIdentifierHeight],
[HKObjectTypeworkoutType]
]];
// 2. Set the types you want to write to HK Store
NSSet *healthKitTypesToWrite = [NSSetsetWithArray:@[
[HKObjectTypequantityTypeForIdentifier:HKQuantityTypeIdentifierBodyMassIndex],
[HKObjectTypequantityTypeForIdentifier:HKQuantityTypeIdentifierActiveEnergyBurned],
[HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierDistanceWalkingRunning],
[HKObjectTypeworkoutType]
]];
// 3. If the store is not available (for instance, iPad) return an error and don't go on.
if (![HKHealthStoreisHealthDataAvailable]) {
NSError *error = [NSErrorerrorWithDomain:@"com.raywenderlich.tutorials.healthkit"code:2userInfo:@{NSLocalizedDescriptionKey:@"HealthKit is not available in this Device"}];
if (completionBlock !=nil) {
completionBlock(false,error);
}
}
@try {
//兼容iOS 10 必须在info.pilst文件中设置
//Privacy - Health Update Usage Description value不能为空否则审核不过
//Privacy - Health Share Usage Description value不能为空否则审核不过
// 4. Request HealthKit authorization
Health框架的介绍:来源http://zhan.renren.com/daxuebatdaren?gid=3602888498064196199&checked=true
三、读取健康信息
HKHealthStore.h
基础信息:
1. 出生年月
iOS 10 之前
- (nullable NSDate *)dateOfBirthWithError:(NSError **)error
iOS 10 之后
- (nullable NSDateComponents *)dateOfBirthComponentsWithError:(NSError **)error
2.性别 - (nullable HKBiologicalSexObject *)biologicalSexWithError:(NSError **)error;
3. 血型 - (nullable HKBloodTypeObject *)bloodTypeWithError:(NSError **)error;
4. 皮肤类型 - (nullable HKFitzpatrickSkinTypeObject *)fitzpatrickSkinTypeWithError:(NSError **)error
5. 轮椅 - (nullable HKWheelchairUseObject *)wheelchairUseWithError:(NSError **)error
样本类型 查询方法
HKSampleQuery
- (instancetype)initWithSampleType:(HKSampleType *)sampleType
predicate:(nullable NSPredicate *)predicate
limit:(NSUInteger)limit
sortDescriptors:(nullable NSArray
resultsHandler:(void(^)(HKSampleQuery *query, NSArray<__kindof HKSample *> * _Nullable results, NSError * _Nullable error))resultsHandler;
HKSampleType 包括: HKCategoryType、HKCorrelationType、HKDocumentType、HKQuantityType、HKWorkoutType
不同的采样数据对应的类不同
HKQuantityType -> HKQuantitySample {HKQuantityType、HKQuantity}
HKWorkoutType -> 体能训练 HKWorkout {HKWorkoutActivityType 、HKWorkoutEvent、HKQuantity、startDate、endDate、source、metadata、device 等数据}
eg: 采集体重
- (void)readWithWeight:(void(^)(float weight))block;
{
// 采集的样本类型
HKQuantityType *calorieType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierBodyMass];
// 采集样本的 开始 和 结束时间
NSDate *startDate = [NSDate distantPast];
NSDate *endDate = [NSDate new];
NSPredicate *predicate = [HKQuery predicateForSamplesWithStartDate:startDate endDate:endDate options:(HKQueryOptionNone)];
// 排序
NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:HKSampleSortIdentifierStartDate ascending:NO];
// 采样
// limit:1 表示采集样本个数 去最近的一次 体重数据 如果limit : 0 采集多条
HKSampleQuery *sample = [[HKSampleQuery alloc] initWithSampleType:calorieType predicate:predicate limit:1 sortDescriptors:@[sort] resultsHandler:^(HKSampleQuery * _Nonnull query, NSArray<__kindof HKSample *> * _Nullable results, NSError * _Nullable error) {
// 查询结果处理
if (results.count > 0) {
HKQuantitySample *sampl = [results firstObject];
NSNumber *num = [sampl.quantity valueForKey:@"value"] ;
float weight = [num floatValue];
if (block) {
block(weight);
}
}
else{
if (block) {
block(0.0);
}
}
}];
// 去健康查询
[self.healthKitStore executeQuery:sample];
}
四、写入健康数据
HKHealthStore.h
HKObject 包括: HKSample {HKWorkout、HKQuantitySample}
写入方法:- (void)saveObject:(HKObject *)object withCompletion:(void(^)(BOOL success, NSError * _Nullable error))completion;
HKWorkout 体能训练创建的方法
HKWorkoutActivityType 为系统的一个枚举 有系统默认几十项运动
metadata 为一个字典,对应的Key和Value 在健康列表中可以提醒 为标题和内容。
+ (instancetype)workoutWithActivityType:(HKWorkoutActivityType)workoutActivityType
startDate:(NSDate *)startDate
endDate:(NSDate *)endDate
workoutEvents:(nullable NSArray
totalEnergyBurned:(nullable HKQuantity *)totalEnergyBurned
totalDistance:(nullable HKQuantity *)totalDistance
metadata:(nullable NSDictionary
HKQuantitySample 写入的样本信息、比较步行、骑车距离、活动能量、爬楼梯等
+ (instancetype)quantitySampleWithType:(HKQuantityType *)quantityType
quantity:(HKQuantity *)quantity
startDate:(NSDate *)startDate
endDate:(NSDate *)endDate
metadata:(nullable NSDictionary
HKQuantity 表示某一种数据单位的数量 HKUnit 不同类型的样本类型 对应的 单位不同,不对应会崩溃。
+ (instancetype)quantityWithUnit:(HKUnit *)unit doubleValue:(double)value;