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

[objc] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. #import <UIKit/UIKit.h>  
  2. #import <HealthKit/HealthKit.h>  
  3. @interface ViewController : UIViewController  
  4. @property (nonatomic,strongHKHealthStore *healthStore;  
  5. @end  
ViewController.m

[objc] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. #import "ViewController.h"  
  2.   
  3. @interface ViewController ()  
  4. @property (weak, nonatomic) IBOutlet UILabel *StepsLable;  
  5.   
  6. @end  
  7.   
  8. @implementation ViewController  
  9.   
  10. - (void)viewDidLoad {  
  11.     [super viewDidLoad];  
  12.     self.StepsLable.layer.cornerRadius = self.StepsLable.frame.size.width/2;  
  13.     self.StepsLable.layer.borderColor = [UIColor redColor].CGColor;  
  14.     self.StepsLable.layer.borderWidth = 5;  
  15.     self.StepsLable.layer.masksToBounds = YES;  
  16. }  
  17. #pragma mark 获取权限  
  18. - (IBAction)getAuthority:(id)sender  
  19. {  
  20.     //查看healthKit在设备上是否可用,iPad上不支持HealthKit  
  21.     if (![HKHealthStore isHealthDataAvailable]) {  
  22.         self.StepsLable.text = @"该设备不支持HealthKit";  
  23.     }  
  24.       
  25.     //创建healthStore对象  
  26.     self.healthStore = [[HKHealthStore alloc]init];  
  27.       
  28.     //设置需要获取的权限 这里仅设置了步数  
  29.     HKObjectType *stepType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];  
  30.     NSSet *healthSet = [NSSet setWithObjects:stepType, nil nil];  
  31.       
  32.     //从健康应用中获取权限  
  33.     [self.healthStore requestAuthorizationToShareTypes:nil readTypes:healthSet completion:^(BOOL success, NSError * _Nullable error) {  
  34.         if (success) {  
  35.             //获取步数后我们调用获取步数的方法  
  36.             [self readStepCount];  
  37.         }  
  38.         else  
  39.         {  
  40.             self.StepsLable.text = @"获取步数权限失败";  
  41.         }  
  42.     }];  
  43. }  
  44. #pragma mark 读取步数 查询数据  
  45. - (void)readStepCount  
  46. {  
  47.     //查询采样信息  
  48.     HKSampleType *sampleType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];  
  49.     //NSSortDescriptor来告诉healthStore怎么样将结果排序  
  50.     NSSortDescriptor *start = [NSSortDescriptor sortDescriptorWithKey:HKSampleSortIdentifierStartDate ascending:NO];  
  51.     NSSortDescriptor *end = [NSSortDescriptor sortDescriptorWithKey:HKSampleSortIdentifierEndDate ascending:NO];  
  52.     //获取当前时间  
  53.     NSDate *now = [NSDate date];  
  54.     NSCalendar *calender = [NSCalendar currentCalendar];  
  55.     NSUInteger unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;  
  56.     NSDateComponents *dateComponent = [calender components:unitFlags fromDate:now];  
  57.     int hour = (int)[dateComponent hour];  
  58.     int minute = (int)[dateComponent minute];  
  59.     int second = (int)[dateComponent second];  
  60.     NSDate *nowDay = [NSDate dateWithTimeIntervalSinceNow:  - (hour*3600 + minute * 60 + second) ];  
  61.     //时间结果与想象中不同是因为它显示的是0区  
  62.     NSLog(@"今天%@",nowDay);  
  63.     NSDate *nextDay = [NSDate dateWithTimeIntervalSinceNow:  - (hour*3600 + minute * 60 + second)  + 86400];  
  64.     NSLog(@"明天%@",nextDay);  
  65.     NSPredicate *predicate = [HKQuery predicateForSamplesWithStartDate:nowDay endDate:nextDay options:(HKQueryOptionNone)];  
  66.       
  67.     /*查询的基类是HKQuery,这是一个抽象类,能够实现每一种查询目标,这里我们需要查询的步数是一个HKSample类所以对应的查询类是HKSampleQuery。下面的limit参数传1表示查询最近一条数据,查询多条数据只要设置limit的参数值就可以了*/  
  68.       
  69.     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) {  
  70.         //设置一个int型变量来作为步数统计  
  71.         int allStepCount = 0;  
  72.         for (int i = 0; i < results.count; i ++) {  
  73.             //把结果转换为字符串类型  
  74.             HKQuantitySample *result = results[i];  
  75.             HKQuantity *quantity = result.quantity;  
  76.             NSMutableString *stepCount = (NSMutableString *)quantity;  
  77.             NSString *stepStr =[ NSString stringWithFormat:@"%@",stepCount];  
  78.             //获取51 count此类字符串前面的数字  
  79.             NSString *str = [stepStr componentsSeparatedByString:@" "][0];  
  80.             int stepNum = [str intValue];  
  81.             NSLog(@"%d",stepNum);  
  82.             //把一天中所有时间段中的步数加到一起  
  83.             allStepCount = allStepCount + stepNum;  
  84.         }  
  85.           
  86.         //查询要放在多线程中进行,如果要对UI进行刷新,要回到主线程  
  87.         [[NSOperationQueue mainQueue]addOperationWithBlock:^{  
  88.             self.StepsLable.text = [NSString stringWithFormat:@"%d",allStepCount];  
  89.         }];  
  90.     }];  
  91.     //执行查询  
  92.     [self.healthStore executeQuery:sampleQuery];  
  93. }  
  94. - (void)didReceiveMemoryWarning {  
  95.     [super didReceiveMemoryWarning];  
  96.     // Dispose of any resources that can be recreated.  
  97. }  
  98.   
  99. @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

    [objc] view plain copy
     在CODE上查看代码片派生到我的代码片
    1. #import <UIKit/UIKit.h>  
    2. #import <HealthKit/HealthKit.h>  
    3. @interface ViewController : UIViewController  
    4. @property (nonatomic,strongHKHealthStore *healthStore;  
    5. @end  
    ViewController.m

    [objc] view plain copy
     在CODE上查看代码片派生到我的代码片
    1. #import "ViewController.h"  
    2.   
    3. @interface ViewController ()  
    4. @property (weak, nonatomic) IBOutlet UILabel *StepsLable;  
    5.   
    6. @end  
    7.   
    8. @implementation ViewController  
    9.   
    10. - (void)viewDidLoad {  
    11.     [super viewDidLoad];  
    12.     self.StepsLable.layer.cornerRadius = self.StepsLable.frame.size.width/2;  
    13.     self.StepsLable.layer.borderColor = [UIColor redColor].CGColor;  
    14.     self.StepsLable.layer.borderWidth = 5;  
    15.     self.StepsLable.layer.masksToBounds = YES;  
    16. }  
    17. #pragma mark 获取权限  
    18. - (IBAction)getAuthority:(id)sender  
    19. {  
    20.     //查看healthKit在设备上是否可用,iPad上不支持HealthKit  
    21.     if (![HKHealthStore isHealthDataAvailable]) {  
    22.         self.StepsLable.text = @"该设备不支持HealthKit";  
    23.     }  
    24.       
    25.     //创建healthStore对象  
    26.     self.healthStore = [[HKHealthStore alloc]init];  
    27.       
    28.     //设置需要获取的权限 这里仅设置了步数  
    29.     HKObjectType *stepType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];  
    30.     NSSet *healthSet = [NSSet setWithObjects:stepType, nil nil];  
    31.       
    32.     //从健康应用中获取权限  
    33.     [self.healthStore requestAuthorizationToShareTypes:nil readTypes:healthSet completion:^(BOOL success, NSError * _Nullable error) {  
    34.         if (success) {  
    35.             //获取步数后我们调用获取步数的方法  
    36.             [self readStepCount];  
    37.         }  
    38.         else  
    39.         {  
    40.             self.StepsLable.text = @"获取步数权限失败";  
    41.         }  
    42.     }];  
    43. }  
    44. #pragma mark 读取步数 查询数据  
    45. - (void)readStepCount  
    46. {  
    47.     //查询采样信息  
    48.     HKSampleType *sampleType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];  
    49.     //NSSortDescriptor来告诉healthStore怎么样将结果排序  
    50.     NSSortDescriptor *start = [NSSortDescriptor sortDescriptorWithKey:HKSampleSortIdentifierStartDate ascending:NO];  
    51.     NSSortDescriptor *end = [NSSortDescriptor sortDescriptorWithKey:HKSampleSortIdentifierEndDate ascending:NO];  
    52.     //获取当前时间  
    53.     NSDate *now = [NSDate date];  
    54.     NSCalendar *calender = [NSCalendar currentCalendar];  
    55.     NSUInteger unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;  
    56.     NSDateComponents *dateComponent = [calender components:unitFlags fromDate:now];  
    57.     int hour = (int)[dateComponent hour];  
    58.     int minute = (int)[dateComponent minute];  
    59.     int second = (int)[dateComponent second];  
    60.     NSDate *nowDay = [NSDate dateWithTimeIntervalSinceNow:  - (hour*3600 + minute * 60 + second) ];  
    61.     //时间结果与想象中不同是因为它显示的是0区  
    62.     NSLog(@"今天%@",nowDay);  
    63.     NSDate *nextDay = [NSDate dateWithTimeIntervalSinceNow:  - (hour*3600 + minute * 60 + second)  + 86400];  
    64.     NSLog(@"明天%@",nextDay);  
    65.     NSPredicate *predicate = [HKQuery predicateForSamplesWithStartDate:nowDay endDate:nextDay options:(HKQueryOptionNone)];  
    66.       
    67.     /*查询的基类是HKQuery,这是一个抽象类,能够实现每一种查询目标,这里我们需要查询的步数是一个HKSample类所以对应的查询类是HKSampleQuery。下面的limit参数传1表示查询最近一条数据,查询多条数据只要设置limit的参数值就可以了*/  
    68.       
    69.     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) {  
    70.         //设置一个int型变量来作为步数统计  
    71.         int allStepCount = 0;  
    72.         for (int i = 0; i < results.count; i ++) {  
    73.             //把结果转换为字符串类型  
    74.             HKQuantitySample *result = results[i];  
    75.             HKQuantity *quantity = result.quantity;  
    76.             NSMutableString *stepCount = (NSMutableString *)quantity;  
    77.             NSString *stepStr =[ NSString stringWithFormat:@"%@",stepCount];  
    78.             //获取51 count此类字符串前面的数字  
    79.             NSString *str = [stepStr componentsSeparatedByString:@" "][0];  
    80.             int stepNum = [str intValue];  
    81.             NSLog(@"%d",stepNum);  
    82.             //把一天中所有时间段中的步数加到一起  
    83.             allStepCount = allStepCount + stepNum;  
    84.         }  
    85.           
    86.         //查询要放在多线程中进行,如果要对UI进行刷新,要回到主线程  
    87.         [[NSOperationQueue mainQueue]addOperationWithBlock:^{  
    88.             self.StepsLable.text = [NSString stringWithFormat:@"%d",allStepCount];  
    89.         }];  
    90.     }];  
    91.     //执行查询  
    92.     [self.healthStore executeQuery:sampleQuery];  
    93. }  
    94. - (void)didReceiveMemoryWarning {  
    95.     [super didReceiveMemoryWarning];  
    96.     // Dispose of any resources that can be recreated.  
    97. }  
    98.   
    99. @end  

0 0
原创粉丝点击