首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >获取HealthKit中每个日期的步骤总数

获取HealthKit中每个日期的步骤总数
EN

Stack Overflow用户
提问于 2015-04-11 20:04:48
回答 6查看 12.9K关注 0票数 10

每天记录在HealthKit中的总步数最好的方法是什么?使用HKSampleQuery的方法initWithSampleType (见下文),我可以使用NSPredicate为查询设置一个开始日期和结束日期,但是该方法每天返回一个包含多个HKQuantitySamples的数组。

代码语言:javascript
复制
- (instancetype)initWithSampleType:(HKSampleType *)sampleType
                     predicate:(NSPredicate *)predicate
                         limit:(NSUInteger)limit
               sortDescriptors:(NSArray *)sortDescriptors
                resultsHandler:(void (^)(HKSampleQuery *query,
                                         NSArray *results,
                                         NSError *error))resultsHandler

我想我可以查询所有记录的步骤计数,并遍历数组并计算每天的总步骤计数,但我希望有一个更简单的解决方案,因为会有数千个HKSampleQuery对象。有没有办法让initWithSampleType每天返回一个总步数?

EN

回答 6

Stack Overflow用户

回答已采纳

发布于 2015-04-11 21:11:38

你应该使用HKStatisticsCollectionQuery

代码语言:javascript
复制
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *interval = [[NSDateComponents alloc] init];
interval.day = 1;

NSDateComponents *anchorComponents = [calendar components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear
                                                 fromDate:[NSDate date]];
anchorComponents.hour = 0;
NSDate *anchorDate = [calendar dateFromComponents:anchorComponents];
HKQuantityType *quantityType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];

// Create the query
HKStatisticsCollectionQuery *query = [[HKStatisticsCollectionQuery alloc] initWithQuantityType:quantityType
                                                                       quantitySamplePredicate:nil
                                                                                       options:HKStatisticsOptionCumulativeSum
                                                                                    anchorDate:anchorDate
                                                                            intervalComponents:interval];

// Set the results handler
query.initialResultsHandler = ^(HKStatisticsCollectionQuery *query, HKStatisticsCollection *results, NSError *error) {
    if (error) {
        // Perform proper error handling here
        NSLog(@"*** An error occurred while calculating the statistics: %@ ***",error.localizedDescription);
    }

    NSDate *endDate = [NSDate date];
    NSDate *startDate = [calendar dateByAddingUnit:NSCalendarUnitDay
                                             value:-7
                                            toDate:endDate
                                           options:0];

    // Plot the daily step counts over the past 7 days
    [results enumerateStatisticsFromDate:startDate
                                  toDate:endDate
                               withBlock:^(HKStatistics *result, BOOL *stop) {

                                   HKQuantity *quantity = result.sumQuantity;
                                   if (quantity) {
                                       NSDate *date = result.startDate;
                                       double value = [quantity doubleValueForUnit:[HKUnit countUnit]];
                                       NSLog(@"%@: %f", date, value);
                                   }

                               }];
};

[self.healthStore executeQuery:query];
票数 17
EN

Stack Overflow用户

发布于 2016-08-10 14:14:44

端口到Swift而不依赖于SwiftDate库

代码语言:javascript
复制
    let calendar = NSCalendar.current
    let interval = NSDateComponents()
    interval.day = 1

    var anchorComponents = calendar.dateComponents([.day, .month, .year], from: NSDate() as Date)
    anchorComponents.hour = 0
    let anchorDate = calendar.date(from: anchorComponents)

    // Define 1-day intervals starting from 0:00
    let stepsQuery = HKStatisticsCollectionQuery(quantityType: stepsCount!, quantitySamplePredicate: nil, options: .cumulativeSum, anchorDate: anchorDate!, intervalComponents: interval as DateComponents)

    // Set the results handler
    stepsQuery.initialResultsHandler = {query, results, error in
        let endDate = NSDate()
        let startDate = calendar.date(byAdding: .day, value: -7, to: endDate as Date, wrappingComponents: false)
        if let myResults = results{
            myResults.enumerateStatistics(from: startDate!, to: endDate as Date) { statistics, stop in
            if let quantity = statistics.sumQuantity(){
                let date = statistics.startDate
                let steps = quantity.doubleValue(for: HKUnit.count())
                print("\(date): steps = \(steps)")
                //NOTE: If you are going to update the UI do it in the main thread
                DispatchQueue.main.async {
                    //update UI components
                }

            }
            } //end block
        } //end if let
    }
    healthStore?.execute(stepsQuery)
票数 9
EN

Stack Overflow用户

发布于 2017-11-06 19:54:02

使用核心Swift类修改@sebastianr的答案,只为测试我只返回一天的步骤,一旦您有更多的时间,您可以创建一个日期字典和步骤计数并返回它

代码语言:javascript
复制
func getStepCountPerDay(completion:@escaping (_ count: Double)-> Void){

    guard let sampleType = HKObjectType.quantityType(forIdentifier: .stepCount)
        else {
            return
    }
    let calendar = Calendar.current
    var dateComponents = DateComponents()
    dateComponents.day = 1

    var anchorComponents = calendar.dateComponents([.day, .month, .year], from: Date())
    anchorComponents.hour = 0
    let anchorDate = calendar.date(from: anchorComponents)

    let stepsCumulativeQuery = HKStatisticsCollectionQuery(quantityType: sampleType, quantitySamplePredicate: nil, options: .cumulativeSum, anchorDate: anchorDate!, intervalComponents: dateComponents
    )

    // Set the results handler
    stepsCumulativeQuery.initialResultsHandler = {query, results, error in
        let endDate = Date()
        let startDate = calendar.date(byAdding: .day, value: 0, to: endDate, wrappingComponents: false)
        if let myResults = results{
            myResults.enumerateStatistics(from: startDate!, to: endDate as Date) { statistics, stop in
                if let quantity = statistics.sumQuantity(){
                    let date = statistics.startDate
                    let steps = quantity.doubleValue(for: HKUnit.count())
                    print("\(date): steps = \(steps)")
                    completion(steps)
                    //NOTE: If you are going to update the UI do it in the main thread
                    DispatchQueue.main.async {
                        //update UI components
                    }
                }
            } //end block
        } //end if let
    }
    HKHealthStore().execute(stepsCumulativeQuery)
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29582462

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档