1.如下图所示 在Xcode中打开HealthKit功能
2.在需要的地方#import (这里我为了方便直接在viewController写了所有代码,我也在学习这个框架,个人感觉把获取数据权限的代码放在AppDelegate中更好)
获取步数分为两步1.获得权限 2.读取步数
3.StoryBoard设计
4.代码部分
ViewController.h
- #import
- #import
- @interface
ViewController : UIViewController - @property
(nonatomic,strong) HKHealthStore *healthStore; - @end
ViewController.m
- #import
"ViewController.h" -
- @interface
ViewController () - @property
(weak, nonatomic) IBOutlet UILabel *StepsLable; -
- @end
-
- @implementation
ViewController -
- -
(void)viewDidLoad { -
[super viewDidLoad]; -
self.StepsLable.layer.cornerRadius = self.StepsLable.frame.size.width/2; -
self.StepsLable.layer.borderColor = [UIColor redColor].CGColor; -
self.StepsLable.layer.borderWidth = 5; -
self.StepsLable.layer.masksToBounds = YES; - }
- #pragma
mark 获取权限 - -
(IBAction)getAuthority:(id)sender - {
-
//查看healthKit在设备上是否可用,iPad上不支持HealthKit -
if (![HKHealthStore isHealthDataAvailable]) { -
self.StepsLable.text = @"该设备不支持HealthKit"; -
} -
-
//创建healthStore对象 -
self.healthStore = [[HKHealthStore alloc]init]; -
//设置需要获取的权限 这里仅设置了步数 -
HKObjectType *stepType = [HKObjectType quantityTypeForIdentifie r:HKQuantityTypeIdentifier StepCount]; -
NSSet *healthSet = [NSSet setWithObjects:stepType,nil]; -
-
//从健康应用中获取权限 -
[self.healthStore requestAuthorizationToSh areTypes:nil readTypes:healthSet completion:^(BOOL success, NSError * _Nullable error) { -
if (success) { -
//获取步数后我们调用获取步数的方法 -
[self readStepCount]; -
} -
else -
{ -
self.StepsLable.text = @"获取步数权限失败"; -
} -
}]; - }
- #pragma
mark 读取步数 查询数据 - -
(void)readStepCount - {
-
//查询采样信息 -
HKSampleType *sampleType = [HKQuantityType quantityTypeForIdentifie r:HKQuantityTypeIdentifier StepCount]; -
//NSSortDescriptor来告诉healthStore怎么样将结果排序 -
NSSortDescriptor *start = [NSSortDescriptor sortDescriptorWithKey:HKSampleSortIdentifierSt artDate ascending:NO]; -
NSSortDescriptor *end = [NSSortDescriptor sortDescriptorWithKey:HKSampleSortIdentifierEn dDate ascending:NO]; -
//获取当前时间 -
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 dateWithTimeIntervalSinc eNow: - (hour*3600 + minute * 60 + second) ]; -
//时间结果与想象中不同是因为它显示的是0区 -
NSLog(@"今天%@",nowDay); -
NSDate *nextDay = [NSDate dateWithTimeIntervalSinc eNow: - (hour*3600 + minute * 60 + second) + 86400]; -
NSLog(@"明天%@",nextDay); -
NSPredicate *predicate = [HKQuery predicateForSamplesWithS tartDate:nowDay endDate:nextDay options:(HKQueryOptionNone)]; -
-
-
-
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 componentsSeparatedByStr ing:@" "][0]; -
int stepNum = [str intValue]; -
NSLog(@"%d",stepNum); -
//把一天中所有时间段中的步数加到一起 -
allStepCount = allStepCount + stepNum; -
} -
-
//查询要放在多线程中进行,如果要对UI进行刷新,要回到主线程 -
[[NSOperationQueue mainQueue]addOperationWithBlock:^{ -
self.StepsLable.text = [NSString stringWithFormat:@"%d",allStepCount]; -
}]; -
}]; -
//执行查询 -
[self.healthStore executeQuery:sampleQuery]; - }
- -
(void)didReceiveMemoryWarning { -
[super didReceiveMemoryWarning]; -
// Dispose of any resources that can be recreated. - }
-
- @end
本文展示了如何在iOS应用中使用HealthKit获取用户的步数数据。首先检查HealthKit在设备上的可用性,然后创建HKHealthStore对象并请求获取步数的权限。接着,通过设置查询条件获取当天的步数数据,并将其累加展示在界面上。
638

被折叠的 条评论
为什么被折叠?



