觉得比较好的博客地址:HealthKit框架参考
我参考的博客地址:点击打开链接iOS利用HealthKit框架从健康app中获取步数信息
我学习的论坛地址:healthkit如何获取每天行走的步数?? 求大神解答
微信和QQ的每日步数最近十分火爆,我就想为自己写的项目中添加一个显示每日步数的功能,上网一搜好像并有相关的详细资料,自己动手丰衣足食。
统计步数信息并不需要我们自己去实现,iOS自带的健康app已经为我们统计好了步数数据。
我们只要使用HealthKit框架从健康app中获取这个数据信息就可以了。
对HealthKit框架有了简单的了解后我们就可以开始了。
1.如下图所示 在Xcode中打开HealthKit功能
2.在需要的地方#import <HealthKit/HealthKit.h>(这里我为了方便直接在viewController写了所有代码,我也在学习这个框架,个人感觉把获取数据权限的代码放在AppDelegate中更好)
获取步数分为两步1.获得权限 2.读取步数
3.StoryBoard设计
4.代码部分
ViewController.h
- #import <UIKit/UIKit.h>
- #import <HealthKit/HealthKit.h>
- @interface ViewController : UIViewController
- @property (nonatomic,strong) HKHealthStore *healthStore;
- @end
- #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 quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
- NSSet *healthSet = [NSSet setWithObjects:stepType, nil nil];
- //从健康应用中获取权限
- [self.healthStore requestAuthorizationToShareTypes:nil readTypes:healthSet completion:^(BOOL success, NSError * _Nullable error) {
- if (success) {
- //获取步数后我们调用获取步数的方法
- [self readStepCount];
- }
- else
- {
- self.StepsLable.text = @"获取步数权限失败";
- }
- }];
- }
- #pragma mark 读取步数 查询数据
- - (void)readStepCount
- {
- //查询采样信息
- HKSampleType *sampleType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
- //NSSortDescriptor来告诉healthStore怎么样将结果排序
- NSSortDescriptor *start = [NSSortDescriptor sortDescriptorWithKey:HKSampleSortIdentifierStartDate ascending:NO];
- NSSortDescriptor *end = [NSSortDescriptor sortDescriptorWithKey:HKSampleSortIdentifierEndDate 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 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)];
- /*查询的基类是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;
- }
- //查询要放在多线程中进行,如果要对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
觉得比较好的博客地址:HealthKit框架参考
我参考的博客地址:点击打开链接iOS利用HealthKit框架从健康app中获取步数信息
我学习的论坛地址:healthkit如何获取每天行走的步数?? 求大神解答
微信和QQ的每日步数最近十分火爆,我就想为自己写的项目中添加一个显示每日步数的功能,上网一搜好像并有相关的详细资料,自己动手丰衣足食。
统计步数信息并不需要我们自己去实现,iOS自带的健康app已经为我们统计好了步数数据。
我们只要使用HealthKit框架从健康app中获取这个数据信息就可以了。
对HealthKit框架有了简单的了解后我们就可以开始了。
1.如下图所示 在Xcode中打开HealthKit功能
2.在需要的地方#import <HealthKit/HealthKit.h>(这里我为了方便直接在viewController写了所有代码,我也在学习这个框架,个人感觉把获取数据权限的代码放在AppDelegate中更好)
获取步数分为两步1.获得权限 2.读取步数
3.StoryBoard设计
4.代码部分
ViewController.h
ViewController.m- #import <UIKit/UIKit.h>
- #import <HealthKit/HealthKit.h>
- @interface ViewController : UIViewController
- @property (nonatomic,strong) HKHealthStore *healthStore;
- @end
- #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 quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
- NSSet *healthSet = [NSSet setWithObjects:stepType, nil nil];
- //从健康应用中获取权限
- [self.healthStore requestAuthorizationToShareTypes:nil readTypes:healthSet completion:^(BOOL success, NSError * _Nullable error) {
- if (success) {
- //获取步数后我们调用获取步数的方法
- [self readStepCount];
- }
- else
- {
- self.StepsLable.text = @"获取步数权限失败";
- }
- }];
- }
- #pragma mark 读取步数 查询数据
- - (void)readStepCount
- {
- //查询采样信息
- HKSampleType *sampleType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
- //NSSortDescriptor来告诉healthStore怎么样将结果排序
- NSSortDescriptor *start = [NSSortDescriptor sortDescriptorWithKey:HKSampleSortIdentifierStartDate ascending:NO];
- NSSortDescriptor *end = [NSSortDescriptor sortDescriptorWithKey:HKSampleSortIdentifierEndDate 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 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)];
- /*查询的基类是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;
- }
- //查询要放在多线程中进行,如果要对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
-
本文介绍如何使用HealthKit框架从iOS健康应用中获取用户的步数信息。通过简单几步即可实现,包括启用HealthKit功能、请求权限及读取步数。

681

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



