iOS 获取健康数据 步数

最近的项目内容是给用户的健康数据做一个可视化的表格,现在把步数相关的统计查询之类的都已经完成了。其中遇到不少问题,都是由于不熟悉HeathyKit的操作。写下此文,希望能帮助第一次入手的人:

先上代码,获取相应的权限,这个App自己会弹窗出来提醒:

    if(![HKHealthStore isHealthDataAvailable])
    {
        NSLog(@"设备不支持healthKit");
    }
    else{
        //创建healthStore实例对象
        self.healthStore = [[HKHealthStore alloc] init];
        
        //设置需要获取的权限这里设置步数,活动热量
        HKObjectType *stepCount = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
        HKObjectType *stepCount1 = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierActiveEnergyBurned];
        NSSet *healthSet = [NSSet setWithObjects:stepCount,stepCount1, nil];
        
        //从健康应用中获取权限
        [self.healthStore requestAuthorizationToShareTypes:nil readTypes:healthSet completion:^(BOOL success, NSError * _Nullable error) {
            if (success)
            {
                NSLog(@"获取步数权限成功");
                //获取步数后我们调用获取步数的方法
                [self readStepCount];
            }
            else
            {
                NSLog(@"获取步数权限失败");
            }
        }];
        }

接下来就是最关键的,如何正确使用合适的模块,得到你想要的数据。
1.设置想要获取的样本
2.新建一个查询的操作,并且设置对应的参数,最重要的莫过于 数据来源的时间段SamplePredicate。时间段在我使用的时候出现很多奇怪的问题,但往往都是时区和输出显示的问题。我会在后续的文章中补充时间这一细节。
请参考:
https://www.jianshu.com/p/ef9665c5734e
https://www.jianshu.com/p/7fcea5b65e76

代码如下:

    NSLog(@"查询当日步数");
    /////////////////
    HKQuantityType *quantityType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
    HKStatisticsQuery *query = [[HKStatisticsQuery alloc]initWithQuantityType:quantityType quantitySamplePredicate:[self predicateForSamplesToday] options:HKStatisticsOptionCumulativeSum completionHandler:^(HKStatisticsQuery * _Nonnull query, HKStatistics * _Nullable result, NSError * _Nullable error) {
        if (error) {
            //[self getCMPStepCount: queryResultBlock];
        } else {
            double stepCount = [result.sumQuantity doubleValueForUnit:[HKUnit countUnit]];
            NSLog(@"当天行走步数 = %lf",stepCount);
        }
    }];
    [self.healthStore executeQuery:query];

补充调用函数

#pragma mark - 构造当天时间段查询参数
- (NSPredicate *)predicateForSamplesToday {
    
    NSDate *startDate = [self zeroOfDate];
    NSDate *endDate = [self localOfDate];
    //NSLog(@"开始%@ 结束%@",startDate,endDate);
    NSPredicate *predicate = [HKQuery predicateForSamplesWithStartDate:startDate endDate:endDate options:HKQueryOptionNone];
    return predicate;
}
//和today凌晨 日期的获取相同
- (NSDate *)zeroOfDate
{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [calendar components:NSUIntegerMax fromDate:[NSDate date]];
    components.hour = 0;
    components.minute = 0;
    components.second = 0;

    NSTimeInterval ts = (double)(int)[[calendar dateFromComponents:components] timeIntervalSince1970];
    NSDate * date = [NSDate dateWithTimeIntervalSince1970:ts];
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    //NSLog(@"时区是%@",zone);
    NSInteger interval = [zone secondsFromGMTForDate: date];
    NSDate *localeZeroDate = [date dateByAddingTimeInterval: interval];
    //NSLog(@"本地凌晨时间是%@",localeDate);

    return localeZeroDate;
}
//当前时间
- (NSDate *)localOfDate
{
        NSCalendar *calendar = [NSCalendar currentCalendar];
        NSDateComponents *components = [calendar components:NSUIntegerMax fromDate:[NSDate date]];
        components.hour = 0;
        components.minute = 0;
        components.second = 0;
        
        NSTimeInterval ts = (double)(int)[[calendar dateFromComponents:components] timeIntervalSince1970];
        NSDate * date = [NSDate dateWithTimeIntervalSince1970:ts];
        NSTimeZone *zone = [NSTimeZone systemTimeZone];
        //NSLog(@"时区是%@",zone);
        self.HSFinterval = [zone secondsFromGMTForDate: date];//这里得到
    NSDate *localeDate = [[NSDate date] dateByAddingTimeInterval: self.HSFinterval];
    return localeDate;
}

本篇结束,后续分析设置正确的NSDate

你可能感兴趣的:(iOS 获取健康数据 步数)