iOS1iOS 开发成长中心iOS Developer

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

2017-04-19  本文已影响267人  爱吃鱼的小灰
一. 使用框架

1.png

打开按钮之后,左侧会自动导入框架


2.png

在需要使用的页面导入框架#import <HealthKit/HealthKit.h>

二. 代码部分
首先声明一个HKHealthStore类的实例,去获取在健康里面获取数据的权限,在iPad上面是不支持此框架的,所以我们要进行一个判断:

if (![HKHealthStore isHealthDataAvailable]) { NSLog(@"该设备不支持HealthKit"); }

如果不是iPad正式开始获取权限:

//创建healthStore对象 
self.healthStore = [[HKHealthStore alloc]init]; 
//设置需要获取的权限 这里仅设置了步数 
HKObjectType *stepType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount]; 
NSSet *healthSet = [NSSet setWithObjects:stepType, nil]; 
//从健康应用中获取权限 
[self.healthStore requestAuthorizationToShareTypes:nil  readTypes:healthSet completion:^(BOOL success, NSError * _Nullable error) {
 if (success) {
 //获取步数后我们调用获取步数的方法
 [self readStepCount]; 
} else {
 NSLog(@"获取步数权限失败"); 
}
 }];

接下来需要实现获取步数的方法代码:
(1)查询采样信息

HKSampleType *sampleType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];

(2)NSSortDescriptor来告诉healthStore怎么样将结果排序

NSSortDescriptor *start = [NSSortDescriptor sortDescriptorWithKey:HKSampleSortIdentifierStartDate ascending:NO]; 
NSSortDescriptor *end = [NSSortDescriptor sortDescriptorWithKey:HKSampleSortIdentifierEndDate ascending:NO];

(3)由于健康中的数据也是通过时间来获取的,所以这里我们要获取当前时间进行对比

NSDate *now = [NSDate date]; 
NSCalendar *calender = [NSCalendar currentCalendar];
 NSUInteger unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
 NSDateComponents *dateComponent = [calender components:unitFlags fromDate:now];
 int hour = (int)[dateComponent hour]; 
int minute = (int)[dateComponent minute]; 
int second = (int)[dateComponent second];
 NSDate *nowDay = [NSDate dateWithTimeIntervalSinceNow: - (hour*3600 + minute * 60 + second) ]; 
//时间结果与想象中不同是因为它显示的是0区 NSLog(@"今天%@",nowDay);
 NSDate *nextDay = [NSDate dateWithTimeIntervalSinceNow: - (hour*3600 + minute * 60 + second) + 86400]; 
NSLog(@"明天%@",nextDay);
 NSPredicate *predicate = [HKQuery predicateForSamplesWithStartDate:nowDay endDate:nextDay options:(HKQueryOptionNone)];

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

HKSampleQuery *sampleQuery = [[HKSampleQuery alloc]initWithSampleType:sampleType predicate:predicate limit:0 sortDescriptors:@[start,end] resultsHandler:^(HKSampleQuery * _Nonnull query, NSArray<__kindof HKSample *> * _Nullable results, NSError * _Nullable error) { 
//设置一个int型变量来作为步数统计 int allStepCount = 0; 
for (int i = 0; i < results.count; i ++) { 
//把结果转换为字符串类型 
HKQuantitySample *result = results[i]; 
HKQuantity *quantity = result.quantity; 
NSMutableString *stepCount = (NSMutableString *)quantity;
 NSString *stepStr =[ NSString stringWithFormat:@"%@",stepCount]; 
//获取51 count此类字符串前面的数字
 NSString *str = [stepStr componentsSeparatedByString:@" "][0]; 
int stepNum = [str intValue];
 NSLog(@"%d",stepNum);
 //把一天中所有时间段中的步数加到一起 
allStepCount = allStepCount + stepNum;
 } 
NSLog(@"今天的总步数====%d",allStepCount); }];

(5)开始执行查询

[self.healthStore executeQuery:sampleQuery];

这样就实现了获取今天到现在为止的步数

上一篇 下一篇

猜你喜欢

热点阅读