ios 健康HealthKit的数据采样

时间:2020-12-03 15:44:39

#import <HealthKit/HealthKit.h>

@property (nonatomic,strong)HKHealthStore *healthStore;

@property (nonatomic,strong)UILabel *stepLabel;

- (void)viewDidLoad {

    

    [superviewDidLoad];


//查看healthKit在设备上是否可用,ipad不支持HealthKit

    if(![HKHealthStoreisHealthDataAvailable])

    {

        NSLog(@"设备不支持healthKit");

    }

    //创建healthStore实例对象

    self.healthStore = [[HKHealthStorealloc]init];

    //设置需要获取的权限这里仅设置了步数

    HKObjectType *stepCount = [HKObjectTypequantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];

    NSSet *healthSet = [NSSetsetWithObjects:stepCount,nil];

    //从健康应用中获取权限

    [self.healthStorerequestAuthorizationToShareTypes:nilreadTypes:healthSetcompletion:^(BOOL success,NSError *_Nullable error) {

        if (success)

        {

            NSLog(@"获取步数权限成功");

            

            [selfreadStepCount];

        }

        else

        {

            NSLog(@"获取步数权限失败");

        }

    }];

}




- (void)readStepCount

{

//    NSCalendar *calendar = [NSCalendar currentCalendar];

//    NSDate *now = [NSDate date];//现在时间转换成UTC时间

//    NSDateComponents *components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:now];

//    NSDate *startDate = [calendar dateFromComponents:components];//今天零点转换成UTC时间 2016-07-04 16:00:00 +0000

//    NSLog(@"%@",startDate);

    //NSDate *endDate = [calendar dateByAddingUnit:NSCalendarUnitDay value:1 toDate:startDate options:0];

    //NSLog(@"%@",endDate);

   

    

    NSDateFormatter *df = [[NSDateFormatteralloc]init];

    df.dateFormat  =@"yyyy/MM/dd HH:mm:ss";

    NSDate *fromDate = [dfdateFromString:@"2016/07/06 13:42:00"];

    NSDate *toDate = [dfdateFromString:@"2016/07/06 13:42:59"];

    

    

    

//    NSDate* fromDate   = [[NSDate alloc] initWithTimeIntervalSinceNow: -60];//距现在时间一分钟之前(NSTimeInterval)

//    NSDate*  toDate  = [[NSDate alloc] init];//现在时间  [NSDate date];//现在时间转换成UTC时间

//    NSCalendar* chineseClendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];

//    NSUInteger unitFlags =

//    NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond | NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear;//252

//    NSDateComponents *cps = [chineseClendar components:unitFlags fromDate:startDate2  toDate:toDate  options:0];

//    NSInteger diffHour = [cps hour];

//    NSInteger diffMin    = [cps minute];

//    NSInteger diffSec   = [cps second];

//    NSInteger diffDay   = [cps day];

//    NSInteger diffMon  = [cps month];

//    NSInteger diffYear = [cps year];

//    NSLog(  @" From Now to %@, diff: Years: %ld  Months: %ld, Days; %ld, Hours: %ld, Mins:%ld, sec:%ld",

//          [toDate description], diffYear, diffMon, diffDay, diffHour, diffMin,diffSec );

    

    

    

    

    

    //查询的基类是HKQuery,这是一个抽象类,能够实现每一种查询目标

    //查询采样信息

    HKSampleType *sampleType = [HKQuantityTypequantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];

    

    //    //NSSortDescriptors用来告诉healthStore

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

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

    

    //predicate 使基于 startDate endDate时间更为过去

    NSPredicate *predicate = [HKQuerypredicateForSamplesWithStartDate:fromDateendDate:toDateoptions:HKQueryOptionNone];

    //limit1表示查询最近1条的数据  sort排序

    HKSampleQuery *query = [[HKSampleQueryalloc]initWithSampleType:sampleTypepredicate:predicatelimit:HKObjectQueryNoLimitsortDescriptors:nilresultsHandler:^(HKSampleQuery *query,NSArray *results, NSError *error) {

        if (!results) {

            NSLog(@"An error occured fetching the user's tracked food. In your app, try to handle this gracefully. The error was: %@.", error);

            //abort();

        }

        

        dispatch_async(dispatch_get_main_queue(), ^{

            //打印查询结果

            NSLog(@"resultCount = %lud result = %@",results.count,results);

            

            if (results.count >0) {

                int step =0;

                for (HKQuantitySample *resultin results) {

                    //对结果进行单位换算

                    HKQuantity *quantity = result.quantity;

                    

                    NSNumber *str = [quantityvalueForKey:@"value"];

                    int unitStep = [strintValue];

                    step+=unitStep;

                }

                self.stepLabel.text = [NSStringstringWithFormat:@"总步数:%d",step];

            }

            

        });

    }];

    [self.healthStoreexecuteQuery:query];

}



fromDate  2016/07/06 13:42:00

toDate    2016/07/06 13:42:59

fromDate~toDate 我称之为采样时间段


41:38—42:27   手机17步数            48:25 添加至健康     我称之为运动时间段1  只进入采样时间段一点

42:06–42:29    手表29步数            43:36 添加至健康    我称之为运动时间段2   完全在采样时间段内

 



查询数据时回返回 运动时间段1 和  运动时间段2  的数据

可以看出只要某一“运动时间段”的运动范围进入了 “采样时间段”,不需要完全进入,这个“运动时间段”的数据就会被采样走