本来以为以后可以好好种树的,结果发现添加的数据可以在健康里面看到,但是无法在支付宝这些里面获取。。。
1,Xcode 8之后需要在info.plist 中设置以下两个权限;
(1)Privacy - Health Update Usage Description
(2)Privacy - Health Share Usage Description
2,导入头文件;
#import <HealthKit/HealthKit.h>
#import <UIKit/UIDevice.h>
3,设置读取数据的权限和写入数据的权限
#pragma mark - 设置写入权限
- (NSSet *)dataTypesToWrite {
HKQuantityType *stepType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
HKQuantityType *distanceType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierDistanceWalkingRunning];
return [NSSet setWithObjects:stepType,distanceType, nil];
}
#pragma mark - 设置读取权限
- (NSSet *)dataTypesToRead {
以下为设置的权限类型:
HKQuantityType *stepType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
HKQuantityType *distanceType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierDistanceWalkingRunning];
return [NSSet setWithObjects:stepType,distanceType, nil];
}
以下是关于fitness的全部权限介绍可以直接去看HKQuantityType.h文件很详细,有//fitness,// Body Measurements,// Results,// Vitals等
// Fitness
HK_EXTERN HKQuantityTypeIdentifier const HKQuantityTypeIdentifierStepCount HK_AVAILABLE_IOS_WATCHOS(8_0, 2_0); // Scalar(Count), Cumulative
HK_EXTERN HKQuantityTypeIdentifier const HKQuantityTypeIdentifierDistanceWalkingRunning HK_AVAILABLE_IOS_WATCHOS(8_0, 2_0); // Length, Cumulative
HK_EXTERN HKQuantityTypeIdentifier const HKQuantityTypeIdentifierDistanceCycling HK_AVAILABLE_IOS_WATCHOS(8_0, 2_0); // Length, Cumulative
HK_EXTERN HKQuantityTypeIdentifier const HKQuantityTypeIdentifierDistanceWheelchair HK_AVAILABLE_IOS_WATCHOS(10_0, 3_0); // Length, Cumulative
HK_EXTERN HKQuantityTypeIdentifier const HKQuantityTypeIdentifierBasalEnergyBurned HK_AVAILABLE_IOS_WATCHOS(8_0, 2_0); // Energy, Cumulative
HK_EXTERN HKQuantityTypeIdentifier const HKQuantityTypeIdentifierActiveEnergyBurned HK_AVAILABLE_IOS_WATCHOS(8_0, 2_0); // Energy, Cumulative
HK_EXTERN HKQuantityTypeIdentifier const HKQuantityTypeIdentifierFlightsClimbed HK_AVAILABLE_IOS_WATCHOS(8_0, 2_0); // Scalar(Count), Cumulative
HK_EXTERN HKQuantityTypeIdentifier const HKQuantityTypeIdentifierNikeFuel HK_AVAILABLE_IOS_WATCHOS(8_0, 2_0); // Scalar(Count), Cumulative
HK_EXTERN HKQuantityTypeIdentifier const HKQuantityTypeIdentifierAppleExerciseTime HK_AVAILABLE_IOS_WATCHOS(9_3, 2_2); // Time Cumulative
HK_EXTERN HKQuantityTypeIdentifier const HKQuantityTypeIdentifierPushCount HK_AVAILABLE_IOS_WATCHOS(10_0, 3_0); // Scalar(Count), Cumulative
HK_EXTERN HKQuantityTypeIdentifier const HKQuantityTypeIdentifierDistanceSwimming HK_AVAILABLE_IOS_WATCHOS(10_0, 3_0); // Length, Cumulative
HK_EXTERN HKQuantityTypeIdentifier const HKQuantityTypeIdentifierSwimmingStrokeCount HK_AVAILABLE_IOS_WATCHOS(10_0, 3_0); // Scalar(Count), Cumulative
4,判断设备是否支持
if(![HKHealthStore isHealthDataAvailable]){
NSLog(@"设备不支持healthkit");
}
5,获取权限和获取数据
// 此处获取权限的写入和读取 获取之后才可以加到数据中
NSSet *writeDataTypes = [self dataTypesToWrite];
NSSet *readDataTypes = [self dataTypesToRead];
[self.healthstore requestAuthorizationToShareTypes:writeDataTypes readTypes:readDataTypes completion:^(BOOL success, NSError * _Nullable error) {
if (success) {
[self getStepsFromHealthKit];//第二种获取方法
// [self getdistanceFromHealthKit]; //获取公里数
}else{
}
}];
6,获取具体的数据的方法,三个方法是一起的//unit此处需要注意的是单位的不同
- (void)getDistancesFromHealthKit{
HKQuantityType *stepType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierDistanceWalkingRunning];
[self fetchSumOfSamplesTodayForType:stepType unit:[HKUnit meterUnit] completion:^(double stepCount, NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"你的公里数为:%.f",stepCount);
self.pedoLab.text = [NSString stringWithFormat:@"%.2fm",stepCount];
});
}];
}
#pragma mark - 读取HealthKit数据
- (void)fetchSumOfSamplesTodayForType:(HKQuantityType *)quantityType unit:(HKUnit *)unit completion:(void (^)(double, NSError *))completionHandler {
NSPredicate *predicate = [self predicateForSamplesToday];
HKStatisticsQuery *query = [[HKStatisticsQuery alloc] initWithQuantityType:quantityType quantitySamplePredicate:predicate options:HKStatisticsOptionCumulativeSum completionHandler:^(HKStatisticsQuery *query, HKStatistics *result, NSError *error) {
HKQuantity *sum = [result sumQuantity];
NSLog(@"result ==== %@",result);
if (completionHandler) {
double value = [sum doubleValueForUnit:unit];
NSLog(@"sum ==== %@",sum);
NSLog(@"value ===%f",value);
completionHandler(value, error);
}
}];
[self.healthstore executeQuery:query];
}
#pragma mark - NSPredicate数据模型
- (NSPredicate *)predicateForSamplesToday {
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *now = [NSDate date];
NSDate *startDate = [calendar startOfDayForDate:now];
NSDate *endDate = [calendar dateByAddingUnit:NSCalendarUnitDay value:1 toDate:startDate options:0];
return [HKQuery predicateForSamplesWithStartDate:startDate endDate:endDate options:HKQueryOptionStrictStartDate];
}
7,添加和写入数据,并重新获取数据
#pragma mark - 添加步数
- (void)adddistanceWithStepNum:(double)stepNum {
HKQuantitySample *stepCorrelationItem = [self distanceCorrelationWithStepNum:stepNum];
[self.healthstore saveObject:stepCorrelationItem withCompletion:^(BOOL success, NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{
if (success) {
[self.view endEditing:YES];
UIAlertView *doneAlertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"添加成功" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
[doneAlertView show];
//刷新数据 重新获取距离
[self getDistancesFromHealthKit];
}else {
NSLog(@"The error was: %@.", error);
UIAlertView *doneAlertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"添加失败" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
[doneAlertView show];
return ;
}
});
}];
}
- (HKQuantitySample *)distanceCorrelationWithStepNum:(double)stepNum {
NSDate *endDate = [NSDate date];
NSDate *startDate = [NSDate dateWithTimeInterval:-300 sinceDate:endDate];
/**
//这里的quantityWithUnit单位如果不对则会报错注意 ,有以下单位获取下面的对应的健康数据需要注意
+ (instancetype)meterUnitWithMetricPrefix:(HKMetricPrefix)prefix; // m
+ (instancetype)meterUnit; // m
+ (instancetype)inchUnit; // in
+ (instancetype)footUnit; // ft
+ (instancetype)yardUnit HK_AVAILABLE_IOS_WATCHOS(9_0, 2_0); // yd
+ (instancetype)mileUnit; // mi
**/
HKQuantity *stepQuantityConsumed = [HKQuantity quantityWithUnit:[HKUnit meterUnit] doubleValue:stepNum];
HKQuantityType *stepConsumedType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierDistanceWalkingRunning];
NSString *strName = [[UIDevice currentDevice] name];
NSString *strModel = [[UIDevice currentDevice] model];
NSString *strSysVersion = [[UIDevice currentDevice] systemVersion];
NSString *localeIdentifier = [[NSLocale currentLocale] localeIdentifier];
HKDevice *device = [[HKDevice alloc] initWithName:strName manufacturer:@"Apple" model:strModel hardwareVersion:strModel firmwareVersion:strModel softwareVersion:strSysVersion localIdentifier:localeIdentifier UDIDeviceIdentifier:localeIdentifier];
// HKQuantitySample *stepConsumedSample = [HKQuantitySample quantitySampleWithType:stepConsumedType quantity:stepQuantityConsumed startDate:startDate endDate:endDate device:device metadata:nil];
//此处在iOS 8 的系统中使用会崩溃,报错找不到该方法,由于以前一直用iOS10的系统测试的未曾发现这个问题,修改为以下方法即可
HKQuantitySample *stepConsumedSample = [HKQuantitySample quantitySampleWithType:stepConsumedType quantity:stepQuantityConsumed startDate:startDate endDate:endDate];
return stepConsumedSample;
}