iOS开发 ——使用HealthKit获取步数

最近根据项目需求,需要在应用中获取用户走的步数。有三种方式可以进行获取步数的方法:
1、利用HealthKit框架从健康App中去获取步数
2、可以利用废弃的CMStepCounter
3、使用CMPedometer类来获取步数
这篇文章先介绍HealthKit的基本使用。

步骤:
一、使用框架


image.png

二、info.plist文件配置。

<key>NSHealthShareUsageDescription</key>
<string>some string value stating the reason</string>
<key>NSHealthUpdateUsageDescription</key>
<string>some string value stating the reason</string>

不配置info.plist 在运行程序时出现崩溃。

三、代码区
我个人认为在需要的页面进行权限获取比较好一点。
1、在需要使用的页面导入框架 #import <HealthKit/HealthKit.h>
2、首先定义HKHealthStore 属性去获取权限,
@property (nonatomic,strong) HKHealthStore *healthStore;
3、判断设备是否支持查看healthKit数据(ipad是不支持查看healthKit数据的

  //判断设备是否支持查看healthKit数据
  if ([HKHealthStore isHealthDataAvailable]) {
      NSLog(@"设备支持healthKit");
  }

4、获取权限

  //创建healthStore实例对象
  self.healthStore = [[HKHealthStore alloc]init];

  //获取权限
  HKObjectType *setpCount = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];

NSSet *healthSet = [NSSet setWithObjects:setpCount, nil];

//健康中获取权限
[self.healthStore requestAuthorizationToShareTypes:nil readTypes:healthSet completion:^(BOOL success, NSError * _Nullable error) {
    if (success) {
        //权限获取成功 调用获取步数的方法
        [self getStepCount];
    }else{
        NSLog(@"获取步数权限失败");
    }
}];

5、获取数据
查询的基类是HKQuery,这是一个抽象类,能够实现每一种查询目标,这里我们需要查询的步数是一个 HKSample类所对应的查询类就是HKSampleQuery。
下面的limit参数传1表示查询最近一条数据,查询多条数据只要设置limit的参数值就可以了

-(void)getStepCount{
    //查询采样信息
    HKSampleType *sampleType = [HKQuantityType         quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
  //NSSortDescriptors用来告诉healthStore怎么样将结果排序。
  NSSortDescriptor *start = [NSSortDescriptor   sortDescriptorWithKey:HKSampleSortIdentifierStartDate ascending:NO];
  NSSortDescriptor *end = [NSSortDescriptor   sortDescriptorWithKey:HKSampleSortIdentifierEndDate ascending:NO];
  HKSampleQuery *sampleQuery = [[HKSampleQuery     alloc]initWithSampleType:sampleType predicate:nil limit:1       sortDescriptors:@[start,end] resultsHandler:^(HKSampleQuery * _Nonnull query,         NSArray<__kindof HKSample *> * _Nullable results, NSError * _Nullable error) {
        NSLog(@"resultCount = %ld result = %@",results.count,results);
        //把结果转换成字符串类型
      HKQuantitySample *result = results[0];
      HKQuantity *quantity = result.quantity;
      NSString *stepStr = (NSString *)quantity;
      [[NSOperationQueue mainQueue] addOperationWithBlock:^{
        NSLog(@"获取今天到现在为止的步数 %@",stepStr);
    }];
  }];
  //执行查询
  [self.healthStore executeQuery:sampleQuery];

}

20AB545590D02887CDA2C9385241A711.png
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容