iOS使用HHealthKit读取修改健康步数

1.首先打开HealthKit

iOS使用HHealthKit读取修改健康步数_第1张图片





2.导入HealthKit.framework,并且导入头文件

3.获取步数的写入和读取权限;

[objc]  view plain  copy
 
  1. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {  
  2.     // Override point for customization after application launch.  
  3.     [self isHealthDataAvailable];  
  4.     return YES;  
  5. }  
  6.   
  7. #pragma mark - 获取健康权限  
  8. - (void)isHealthDataAvailable{  
  9.     if ([HKHealthStore isHealthDataAvailable]) {  
  10.         HKHealthStore *healthStore = [[HKHealthStore alloc]init];  
  11.         NSSet *writeDataTypes = [self dataTypesToWrite];  
  12.         NSSet *readDataTypes = [self dataTypesToRead];  
  13.         [healthStore requestAuthorizationToShareTypes:writeDataTypes readTypes:readDataTypes completion:^(BOOL success, NSError *error) {  
  14.             if (!success) {  
  15.                 NSLog(@"你不允许包来访问这些读/写数据类型。error === %@", error);  
  16.                 return;  
  17.             }  
  18.         }];  
  19.     }  
  20. }  
  21.   
  22. #pragma mark - 设置写入权限  
  23. - (NSSet *)dataTypesToWrite {  
  24.     HKQuantityType *stepType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];  
  25.     return [NSSet setWithObjects:stepType, nil nil];  
  26. }  
  27.   
  28. #pragma mark - 设置读取权限  
  29. - (NSSet *)dataTypesToRead {  
  30.     HKQuantityType *stepType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];  
  31.     return [NSSet setWithObjects:stepType, nil nil];  
  32. }  

4.获取步数

[objc]  view plain  copy
 
  1. #pragma mark - 获取步数 刷新界面  
  2. - (void)getStepsFromHealthKit{  
  3.     HKQuantityType *stepType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];  
  4.     [self fetchSumOfSamplesTodayForType:stepType unit:[HKUnit countUnit] completion:^(double stepCount, NSError *error) {  
  5.         dispatch_async(dispatch_get_main_queue(), ^{  
  6.             NSLog(@"你的步数为:%.f",stepCount);  
  7.         });  
  8.     }];  
  9. }  

[objc]  view plain  copy
 
  1. #pragma mark - 读取HealthKit数据  
  2. - (void)fetchSumOfSamplesTodayForType:(HKQuantityType *)quantityType unit:(HKUnit *)unit completion:(void (^)(doubleNSError *))completionHandler {  
  3.     NSPredicate *predicate = [self predicateForSamplesToday];  
  4.       
  5.     HKStatisticsQuery *query = [[HKStatisticsQuery alloc] initWithQuantityType:quantityType quantitySamplePredicate:predicate options:HKStatisticsOptionCumulativeSum completionHandler:^(HKStatisticsQuery *query, HKStatistics *result, NSError *error) {  
  6.         HKQuantity *sum = [result sumQuantity];  
  7.         if (completionHandler) {  
  8.             double value = [sum doubleValueForUnit:unit];  
  9.             completionHandler(value, error);  
  10.         }  
  11.     }];  
  12.     [self.healthStore executeQuery:query];  
  13. }  

[objc]  view plain  copy
 
  1. #pragma mark - NSPredicate数据模型  
  2. - (NSPredicate *)predicateForSamplesToday {  
  3.     NSCalendar *calendar = [NSCalendar currentCalendar];  
  4.     NSDate *now = [NSDate date];  
  5.     NSDate *startDate = [calendar startOfDayForDate:now];  
  6.     NSDate *endDate = [calendar dateByAddingUnit:NSCalendarUnitDay value:1 toDate:startDate options:0];  
  7.     return [HKQuery predicateForSamplesWithStartDate:startDate endDate:endDate options:HKQueryOptionStrictStartDate];  
  8. }  

5.添加步数

[objc]  view plain  copy
 
  1. #pragma mark - 添加步数  
  2. - (void)addstepWithStepNum:(double)stepNum {  
  3.     HKQuantitySample *stepCorrelationItem = [self stepCorrelationWithStepNum:stepNum];  
  4.       
  5.     [self.healthStore saveObject:stepCorrelationItem withCompletion:^(BOOL success, NSError *error) {  
  6.         dispatch_async(dispatch_get_main_queue(), ^{  
  7.             if (success) {  
  8.                 [self.view endEditing:YES];  
  9.                 UIAlertView *doneAlertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"添加成功" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil nil];  
  10.                 [doneAlertView show];  
  11.                 //刷新数据  重新获取步数  
  12.                 [self getStepsFromHealthKit];  
  13.             }else {  
  14.                 NSLog(@"The error was: %@.", error);  
  15.                 UIAlertView *doneAlertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"添加失败" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil nil];  
  16.                 [doneAlertView show];  
  17.                 return ;  
  18.             }  
  19.         });  
  20.     }];  
  21. }  
  22.   
  23. #pragma Mark - 获取HKQuantitySample数据模型  
  24. - (HKQuantitySample *)stepCorrelationWithStepNum:(double)stepNum {  
  25.     NSDate *endDate = [NSDate date];  
  26.     NSDate *startDate = [NSDate dateWithTimeInterval:-300 sinceDate:endDate];  
  27.       
  28.     HKQuantity *stepQuantityConsumed = [HKQuantity quantityWithUnit:[HKUnit countUnit] doubleValue:stepNum];  
  29.     HKQuantityType *stepConsumedType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];  
  30.   
  31.     NSString *strName = [[UIDevice currentDevice] name];  
  32.     NSString *strModel = [[UIDevice currentDevice] model];  
  33.     NSString *strSysVersion = [[UIDevice currentDevice] systemVersion];  
  34.     NSString *localeIdentifier = [[NSLocale currentLocale] localeIdentifier];  
  35.       
  36.     HKDevice *device = [[HKDevice alloc] initWithName:strName manufacturer:@"Apple" model:strModel hardwareVersion:strModel firmwareVersion:strModel softwareVersion:strSysVersion localIdentifier:localeIdentifier UDIDeviceIdentifier:localeIdentifier];  
  37.       
  38.     HKQuantitySample *stepConsumedSample = [HKQuantitySample quantitySampleWithType:stepConsumedType quantity:stepQuantityConsumed startDate:startDate endDate:endDate device:device metadata:nil];  
  39.       
  40.     return stepConsumedSample;  
  41. }  

你可能感兴趣的:(iOS使用HHealthKit读取修改健康步数)