HealthKit之实战读取步数、活动时长、运动距离、已爬楼层、活动能量、健身记录

简介:

- (void)queryStepCount

{

    if (![HKHealthStore isHealthDataAvailable])

    {

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

    }

    _healthStore = [[HKHealthStore alloc] init];

    HKObjectType *type1 = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount]; // 步数

    HKObjectType *type2 = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierDistanceWalkingRunning]; // 步行+跑步距离

    HKObjectType *type3 = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierFlightsClimbed];     // 已爬楼层

    HKObjectType *tyep4 = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierActiveEnergyBurned]; // 活动能量

    HKObjectType *type5 = [HKObjectType activitySummaryType];// 健身记录

    NSSet *set = [NSSet setWithObjects:type1, type2, type3, tyep4, type5, nil]; // 读集合

    

    __weak typeof (&*self) weakSelf = self;

    [_healthStore requestAuthorizationToShareTypes:nil readTypes:set completion:^(BOOL success, NSError * _Nullable error) {

        if (success)

        {

            [weakSelf readStepCount];

        } else

        {

            NSLog(@"healthkit不允许读写");

        }

    }];

}


//查询数据

- (void)readStepCount

{

    HKQuantityType *sampleType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];

    

    //NSSortDescriptors用来告诉healthStore怎么样将结果排序。

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

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

    

    /*查询的基类是HKQuery,这是一个抽象类,能够实现每一种查询目标,这里我们需要查询的步数是一个

     HKSample类所以对应的查询类就是HKSampleQuery

     下面的limit参数传1表示查询最近一条数据,查询多条数据只要设置limit的参数值就可以了

     */

    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];

    NSDateComponents *dateCom = [calendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit fromDate:[NSDate date]];

    

    NSDate *startDate, *endDate;

    endDate = [calendar dateFromComponents:dateCom];

    

    [dateCom setHour:0];

    [dateCom setMinute:0];

    [dateCom setSecond:0];

    

    startDate = [calendar dateFromComponents:dateCom];

    NSPredicate *predicate = [HKQuery predicateForSamplesWithStartDate:startDate endDate:endDate options:HKQueryOptionStrictStartDate];

    

    __weak typeof (&*_healthStore)weakHealthStore = _healthStore;

    

    HKSampleQuery *q1 = [[HKSampleQuery alloc] initWithSampleType:sampleType predicate:predicate limit:HKObjectQueryNoLimit sortDescriptors:@[start,end] resultsHandler:^(HKSampleQuery * _Nonnull query, NSArray<__kindof HKSample *> * _Nullable results, NSError * _Nullable error) {

        double sum = 0;

        double sumTime = 0;

        NSLog(@"步数结果=%@", results);

        for (HKQuantitySample *res in results)

        {

            

            sum += [res.quantity doubleValueForUnit:[HKUnit countUnit]];

            

            NSTimeZone *zone = [NSTimeZone systemTimeZone];

            NSInteger interval = [zone secondsFromGMTForDate:res.endDate];

            

            NSDate *startDate = [res.startDate dateByAddingTimeInterval:interval];

            NSDate *endDate   = [res.endDate dateByAddingTimeInterval:interval];


            sumTime += [endDate timeIntervalSinceDate:startDate];

            [[NSOperationQueue mainQueue] addOperationWithBlock:^{

                //查询是在多线程中进行的,如果要对UI进行刷新,要回到主线程中

                self.title = [NSString stringWithFormat:@"运动步数:%@", @(sum).stringValue];

            }];

        }

        int h = sumTime / 3600;

        int m = ((long)sumTime % 3600)/60;

        NSLog(@"运动时长:%@小时%@", @(h), @(m));

        NSLog(@"运动步数:%@", @(sum));

        if(error) NSLog(@"1error==%@", error);

        [weakHealthStore stopQuery:query];

        NSLog(@"\n\n");

    }];

    

    HKSampleType *timeSampleType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierDistanceWalkingRunning];

    HKSampleQuery *q2 = [[HKSampleQuery alloc] initWithSampleType:timeSampleType predicate:predicate limit:HKObjectQueryNoLimit sortDescriptors:@[start,end] resultsHandler:^(HKSampleQuery * _Nonnull query, NSArray<__kindof HKSample *> * _Nullable results, NSError * _Nullable error) {

        double time = 0;

        for (HKQuantitySample *res in results)

        {

            time += [res.quantity doubleValueForUnit:[HKUnit meterUnit]];

        }

        NSLog(@"运动距离===%@", @((long)time));

        if(error) NSLog(@"2error==%@", error);

        [weakHealthStore stopQuery:query];

    }];

    

    HKSampleType *type3 = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierFlightsClimbed];

    HKSampleQuery *q3 = [[HKSampleQuery alloc] initWithSampleType:type3 predicate:predicate limit:HKObjectQueryNoLimit sortDescriptors:@[start,end] resultsHandler:^(HKSampleQuery * _Nonnull query, NSArray<__kindof HKSample *> * _Nullable results, NSError * _Nullable error) {

        double num = 0;

        for (HKQuantitySample *res in results)

        {

            num += [res.quantity doubleValueForUnit:[HKUnit countUnit]];

        }

        NSLog(@"楼层===%@", @(num));

        if(error) NSLog(@"3error==%@", error);

        [weakHealthStore stopQuery:query];

    }];


    HKSampleType *type4 = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierActiveEnergyBurned];

    HKSampleQuery *q4 = [[HKSampleQuery alloc] initWithSampleType:type4 predicate:predicate limit:HKObjectQueryNoLimit sortDescriptors:@[start,end] resultsHandler:^(HKSampleQuery * _Nonnull query, NSArray<__kindof HKSample *> * _Nullable results, NSError * _Nullable error) {

        double num = 0;

        for (HKQuantitySample *res in results)

        {

            num += [res.quantity doubleValueForUnit:[HKUnit kilocalorieUnit]];

        }

        NSLog(@"卡路里===%@大卡", @((long)num));

        if(error) NSLog(@"4error==%@", error);

        [weakHealthStore stopQuery:query];

        NSLog(@"\n\n");

    }];

    

    NSDateComponents *dateCom5B = [calendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:[NSDate date]];

    [dateCom5B setDay:(dateCom5B.day - 10)];

    dateCom5B.calendar = calendar;

    NSDateComponents *dateCom5E = [calendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:[NSDate date]];

    dateCom5E.calendar = calendar;

    NSPredicate *predicate5 = [HKActivitySummaryQuery predicateForActivitySummaryWithDateComponents:dateCom5B];

//    NSPredicate *predicate5 = [HKActivitySummaryQuery predicateForActivitySummariesBetweenStartDateComponents:dateCom5B endDateComponents:dateCom5E];

    HKActivitySummaryQuery *q5 = [[HKActivitySummaryQuery alloc] initWithPredicate:predicate5 resultsHandler:^(HKActivitySummaryQuery * _Nonnull query, NSArray<HKActivitySummary *> * _Nullable activitySummaries, NSError * _Nullable error) {

        double energyNum       = 0;

        double exerciseNum     = 0;

        double standNum        = 0;

        double energyGoalNum   = 0;

        double exerciseGoalNum = 0;

        double standGoalNum    = 0;

        for (HKActivitySummary *summary in activitySummaries)

        {

            energyNum       += [summary.activeEnergyBurned doubleValueForUnit:[HKUnit kilocalorieUnit]];

            exerciseNum     += [summary.appleExerciseTime doubleValueForUnit:[HKUnit secondUnit]];

            standNum        += [summary.appleStandHours doubleValueForUnit:[HKUnit countUnit]];

            energyGoalNum   += [summary.activeEnergyBurnedGoal doubleValueForUnit:[HKUnit kilocalorieUnit]];

            exerciseGoalNum += [summary.appleExerciseTimeGoal doubleValueForUnit:[HKUnit secondUnit]];

            standGoalNum    += [summary.appleStandHoursGoal doubleValueForUnit:[HKUnit countUnit]];

        }

        NSLog(@"\n\n");

        NSLog(@"健身记录:energyNum=%@",       @(energyNum));

        NSLog(@"健身记录:exerciseNum=%@",     @(exerciseNum));

        NSLog(@"健身记录:standNum=%@",        @(standNum));

        NSLog(@"健身记录:energyGoalNum=%@",   @(energyGoalNum));

        NSLog(@"健身记录:exerciseGoalNum=%@", @(exerciseGoalNum));

        NSLog(@"健身记录:standGoalNum=%@",    @(standGoalNum));

        if(error) NSLog(@"5error==%@", error);

        [weakHealthStore stopQuery:query];

        NSLog(@"\n\n");

    }];

       

    //执行查询

    [_healthStore executeQuery:q1];

    [_healthStore executeQuery:q2];

    [_healthStore executeQuery:q3];

    [_healthStore executeQuery:q4];

    [_healthStore executeQuery:q5];

}

码府
+关注
目录
打赏
0
0
0
1
27
分享
相关文章
ATOM机载活动中收集的部分气流和气溶胶粒子现场测量结果(飞机位置、相对湿度、温度、压力、攻角(AOA)、探头位置、真实和探头风速)
该数据集汇总了多次机载活动(如ATom、SALTRACE和A-LIFE)中收集的气流和气溶胶粒子现场测量结果,涵盖2013年至2018年期间的飞行任务。数据包括飞机位置、相对湿度、温度、压力、攻角、探头位置及风速等参数,并结合数值建模模拟粒子采样效率,研究机翼安装仪器对采样影响及不同飞行条件下的误差。这些数据有助于理解大气中的气溶胶分布及其对气候和空气质量的影响。
21 4
|
9月前
|
【unity实战】时间控制 昼夜交替 四季变化 天气变化效果
【unity实战】时间控制 昼夜交替 四季变化 天气变化效果
272 0
如何计算摄影参数:分区基准面高程、相对航高、绝对航高、基线长度、航线间隔、航线数、每条航线的相片数、总相片数。
如何计算摄影参数:分区基准面高程、相对航高、绝对航高、基线长度、航线间隔、航线数、每条航线的相片数、总相片数。
1897 0
微信小程序实现运动步数排行(可删除)
微信小程序实现运动步数排行(可删除)
76 0
走近高德驾车ETA(预估到达时间)
ETA(Estimated Time of Arrival),即预估到达时间,指的是用户在当前时刻出发按照给定路线前往目的地预计需要的时长。如何准确地预估ETA对于高德地图的诸多业务板块都起到至关重要的作用。
走近高德驾车ETA(预估到达时间)
科学家小蓝来到了一个荒岛,准备对这个荒岛进行探测考察。 小蓝使用了一个超声定位设备来对自己进行定位。为了使用这个设备,小蓝需要在不同的点分别安装一个固定的发射器和一个固定的接收器。小蓝手中还有一个移
科学家小蓝来到了一个荒岛,准备对这个荒岛进行探测考察。 小蓝使用了一个超声定位设备来对自己进行定位。为了使用这个设备,小蓝需要在不同的点分别安装一个固定的发射器和一个固定的接收器。小蓝手中还有一个移
294 0
科学家小蓝来到了一个荒岛,准备对这个荒岛进行探测考察。 小蓝使用了一个超声定位设备来对自己进行定位。为了使用这个设备,小蓝需要在不同的点分别安装一个固定的发射器和一个固定的接收器。小蓝手中还有一个移
中秋节祝福程序源代码分享:土地分类数据阈值筛选和重投影分类
中秋节祝福程序源代码分享:土地分类数据阈值筛选和重投影分类
167 0
中秋节祝福程序源代码分享:土地分类数据阈值筛选和重投影分类
LeetCode 2087. 网格图中机器人回家的最小代价(脑筋急转弯)
LeetCode 2087. 网格图中机器人回家的最小代价(脑筋急转弯)
363 0
LeetCode 2087. 网格图中机器人回家的最小代价(脑筋急转弯)
穿科技︱GOW智能T恤衫:时刻记录生命特征
穿科技︱GOW智能T恤衫:时刻记录生命特征
穿科技︱GOW智能T恤衫:时刻记录生命特征
遇到个别手机前置摄像头相差90度的怪事
今天有人提供了一个手机,说怎么视频角度总是不对。吾以为应用版本没有更新。安装之后一试,还是错误,总是跟别的手机相差90度。
171 0

热门文章

最新文章