iOS使用HealthKit获取今天步数
来源:互联网 发布:魅族云相册软件 编辑:程序博客网 时间:2024/05/18 03:31
觉得比较好的博客地址:HealthKit框架参考
我参考的博客地址:点击打开链接iOS利用HealthKit框架从健康app中获取步数信息
我学习的论坛地址:healthkit如何获取每天行走的步数?? 求大神解答
iOS开发-读取健康中的步数和步行+跑步距离
微信和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
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
- {
-
- if (![HKHealthStore isHealthDataAvailable]) {
- self.StepsLable.text = @"该设备不支持HealthKit";
- }
-
-
- 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 *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) ];
-
- NSLog(@"今天%@",nowDay);
- NSDate *nextDay = [NSDate dateWithTimeIntervalSinceNow: - (hour*3600 + minute * 60 + second) + 86400];
- NSLog(@"明天%@",nextDay);
- NSPredicate *predicate = [HKQuery predicateForSamplesWithStartDate: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 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];
-
- NSString *str = [stepStr componentsSeparatedByString:@" "][0];
- int stepNum = [str intValue];
- NSLog(@"%d",stepNum);
-
- allStepCount = allStepCount + stepNum;
- }
-
-
- [[NSOperationQueue mainQueue]addOperationWithBlock:^{
- self.StepsLable.text = [NSString stringWithFormat:@"%d",allStepCount];
- }];
- }];
-
- [self.healthStore executeQuery:sampleQuery];
- }
- - (void)didReceiveMemoryWarning {
- [super didReceiveMemoryWarning];
-
- }
-
- @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
- #import <UIKit/UIKit.h>
- #import <HealthKit/HealthKit.h>
- @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
- {
-
- if (![HKHealthStore isHealthDataAvailable]) {
- self.StepsLable.text = @"该设备不支持HealthKit";
- }
-
-
- 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 *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) ];
-
- NSLog(@"今天%@",nowDay);
- NSDate *nextDay = [NSDate dateWithTimeIntervalSinceNow: - (hour*3600 + minute * 60 + second) + 86400];
- NSLog(@"明天%@",nextDay);
- NSPredicate *predicate = [HKQuery predicateForSamplesWithStartDate: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 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];
-
- NSString *str = [stepStr componentsSeparatedByString:@" "][0];
- int stepNum = [str intValue];
- NSLog(@"%d",stepNum);
-
- allStepCount = allStepCount + stepNum;
- }
-
-
- [[NSOperationQueue mainQueue]addOperationWithBlock:^{
- self.StepsLable.text = [NSString stringWithFormat:@"%d",allStepCount];
- }];
- }];
-
- [self.healthStore executeQuery:sampleQuery];
- }
- - (void)didReceiveMemoryWarning {
- [super didReceiveMemoryWarning];
-
- }
-
- @end
0 0