1.第一步:创建证书和profix文件支持HealthKit;
2.第二步:
3.第三步:设置info.plist
4.第四步
#import <HealthKit/HealthKit.h>
5.第五步
-(HKHealthStore *)healthStore{ if (_healthStore == nil) { _healthStore = [[HKHealthStore alloc] init]; } return _healthStore; }
6.第六步
if ([HKHealthStore isHealthDataAvailable]){ HKQuantityType *heightType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierHeight]; NSSet *writeSet = [NSSet setWithObjects:heightType,nil]; [self.healthStore requestAuthorizationToShareTypes:writeSet readTypes:nil completion:^(BOOL success, NSError * _Nullable error) { //回调值success表明本次授权请求是否发送成功,而不是判断用户是允许OR不允许 NSLog(@"---苹果健康:申请权限请求发送完毕:%d err:%@",success,error); //Xcode提示当前在子线程,需回到主线程刷新UI }];}
7.上传数据
/** * 身高写入健康 * */ - (void)writeToHealthAppSetHeight:(double)heightValue timeStamp:(NSInteger)interval{ if (HKVersion >= 8.0) {
if (heightValue <=0 || interval <0) {
NSLog(@"身高写入健康:数据异常");
return;
}
NSDate *now = [NSDate dateWithTimeIntervalSince1970:interval];
HKQuantityType *heightType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierHeight];
HKQuantity *heightQuantity = [HKQuantity quantityWithUnit:[HKUnit meterUnit] doubleValue:heightValue];
HKQuantitySample *heightSample = [HKQuantitySample quantitySampleWithType:heightType quantity:heightQuantity startDate:now endDate:now]; if ([self.healthStore authorizationStatusForType:heightType] != HKAuthorizationStatusSharingAuthorized) { NSLog(@"没有身高写入权限"); return; } [self.healthStore saveObject:heightSample withCompletion:^(BOOL success, NSError * _Nullable error) { if (success) { NSLog(@"---苹果健康:写入身高成功"); }else { NSLog(@"---苹果健康:写入身高失败"); } }]; } }
网友评论