详解iOS 计步器的几种实现方式

2020-01-21 00:37:44王振洲

4、在info.plist文件中,增加NSHealthShareUsageDescription用于读取数据的描述和NSHealthUpdateUsageDescription用于写入数据的描述

5、用户授权之后,就可以对健康数据中授权的项目进行读取或写入操作。下面的代码是查询一段历史的计步记录的示例,如CMPedemoter不同的是查询到的数据不是实时更新的。


   // 查询数据的类型,比如计步,行走+跑步距离等等 
   HKQuantityType *quantityType = [HKQuantityType quantityTypeForIdentifier:(HKQuantityTypeIdentifierStepCount)];
   // 谓词,用于限制查询返回结果
   NSPredicate *predicate = [HKQuery predicateForSamplesWithStartDate:start endDate:end options:(HKQueryOptionNone)];

   NSCalendar *calendar = [NSCalendar currentCalendar];
   NSDateComponents *anchorComponents = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:[NSDate date]];
   // 用于锚集合的时间间隔
   NSDate *anchorDate = [calendar dateFromComponents:anchorComponents];

   // 采样时间间隔
   NSDateComponents *intervalComponents = [[NSDateComponents alloc] init];
   intervalComponents.day = 1;
   
   // 创建统计查询对象
   HKStatisticsCollectionQuery *query = [[HKStatisticsCollectionQuery alloc] initWithQuantityType:quantityType quantitySamplePredicate:predicate options:(HKStatisticsOptionCumulativeSum|HKStatisticsOptionSeparateBySource) anchorDate:anchorDate intervalComponents:intervalComponents];
   query.initialResultsHandler = ^(HKStatisticsCollectionQuery * _Nonnull query, HKStatisticsCollection * _Nullable result, NSError * _Nullable error) {
     NSMutableArray *resultArr = [NSMutableArray array];
     if (error) {
       NSLog(@"error: %@", error);
     } else {
     for (HKStatistics *statistics in [result statistics]) {
       NSLog(@"statics: %@,n sources: %@", statistics, statistics.sources);
       for (HKSource *source in statistics.sources) {
         // 过滤掉其它应用写入的健康数据
         if ([source.name isEqualToString:[UIDevice currentDevice].name]) {
           // 获取到步数
           double step = round([[statistics sumQuantityForSource:source] doubleValueForUnit:[HKUnit countUnit]]); 
         }
       }
     }
   }
   // 执行查询请求
   [self.healthStore executeQuery:query];

如果要写入数据到苹果HealtkKit中,过程类似,下面的示例是写入步数到健康数据。(QQ中运动的步数和Keep中的步数都是从健康数据中获取的步数,而且没有过滤其它应用写入的数据,所以想要修改QQ或Keep中的步数,可以用自己的app写入步数数据,亲测有效)

①请求用户授权


  HKQuantityType *stepType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
  NSSet *shareTypes = [NSSet setWithObjects:stepType, nil];
 [self.healthStore requestAuthorizationToShareTypes:shareTypes readTypes:nil completion:^(BOOL success, NSError * _Nullable error) {

 }];