查询HealthKit了解当天的总步数

时间:2016-11-16 07:16:18

标签: ios objective-c health-kit

我正在调用一个函数,并且一直在试图弄清楚如何更新我的应用以反映当天的总步数。目前,我的代码只给出了我记录的最新步骤数量。我无法理解如何使用HKStatisticsQuery,但这是我现有的功能,它给了我最新的结果。

-(void)updateStepsLabel{
        // Query to get the user's latest steps, if it exists.
HKQuantityType *stepsType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];

[_healthStore aapl_mostRecentQuantitySampleOfType:stepsType predicate:nil completion:^(HKQuantity *mostRecentQuantity, NSError *error) {
    if (!mostRecentQuantity) {
        NSLog(@"Either an error occured fetching the user's steps information or none has been stored yet. In your app, try to handle this gracefully.");

        dispatch_async(dispatch_get_main_queue(), ^{
            self.todaysStepValueLabel.text = NSLocalizedString(@"Not available", nil);
        });
    }
    else {
        // Determine the steps in the required unit.
        HKUnit *stepUnit = [HKUnit countUnit];
        double usersWeight = [mostRecentQuantity doubleValueForUnit:stepUnit];

        // Update the user interface.
        dispatch_async(dispatch_get_main_queue(), ^{
            self.todaysStepValueLabel.text = [NSNumberFormatter localizedStringFromNumber:@(usersWeight) numberStyle:NSNumberFormatterNoStyle];
            self.todaysStepValueLabel.textColor = [UIColor blackColor];
            self.todaysStepValueLabel.font = [UIFont systemFontOfSize:25];


        });
    }
}];

}

2 个答案:

答案 0 :(得分:1)

这里我发布了Swift代码的答案,希望你能将它转换成Obj-c

我在类中定义了以下函数,如下所示

class MyHealthStore: HKHealthStore { }

func TodayTotalSteps(completion: (stepRetrieved: Double) -> Void) {

    let type = HKSampleType.quantityTypeForIdentifier(HKQuantityTypeIdentifierStepCount) // The type of data we are requesting

    let calendar = NSCalendar.currentCalendar()
    let interval = NSDateComponents()
    interval.day = 1

    let anchorComponents = calendar.components([.Day , .Month , .Year], fromDate: NSDate())
    anchorComponents.hour = 0
    let anchorDate = calendar.dateFromComponents(anchorComponents)

    let stepsQuery = HKStatisticsCollectionQuery(quantityType: type!, quantitySamplePredicate: nil, options: .CumulativeSum, anchorDate: anchorDate!, intervalComponents: interval)

    stepsQuery.initialResultsHandler = {query, results, error in
        let endDate = NSDate()

        var totalSteps = 0.0
        let startDate = calendar.dateByAddingUnit(.Day, value: 0, toDate: endDate, options: [])
        if let myResults = results{  myResults.enumerateStatisticsFromDate(startDate!, toDate: endDate) { statistics, stop in
            if let quantity = statistics.sumQuantity(){
                //let date = statistics.startDate
                totalSteps = quantity.doubleValueForUnit(HKUnit.countUnit())
               // print("\(date): steps = \(steps)")
            }
            self.todayManuallyAddedSteps({ (manuallSteps, error) in
                if error != nil {
                    print(error)
                } else {
                   totalSteps = totalSteps - manuallSteps
                    completion(stepRetrieved: totalSteps)
                    return
                }
            })
            //completion(stepRetrieved: totalSteps)

            }
        } else {
            // mostly not executed
            completion(stepRetrieved: totalSteps)
        }
    }
    executeQuery(stepsQuery)
}

如果您想截断手动添加的步骤,请使用此功能

func todayManuallyAddedSteps(completion: (Double, NSError?) -> () )
{
    let type = HKSampleType.quantityTypeForIdentifier(HKQuantityTypeIdentifierStepCount) // The type of data we are requesting

    let date = NSDate()
    let cal = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
    let newDate = cal.startOfDayForDate(date)
    let predicate = HKQuery.predicateForSamplesWithStartDate(newDate, endDate: NSDate(), options: .None) // Our search predicate which will fetch all steps taken today

    // The actual HealthKit Query which will fetch all of the steps and add them up for us.

    let query = HKSampleQuery(sampleType: type!, predicate: predicate, limit: 0, sortDescriptors: nil) { query, results, error in
        var steps: Double = 0

        if results?.count > 0
        {
            for result in results as! [HKQuantitySample]
            {
                // checking and adding manually added steps
                if result.sourceRevision.source.name == "Health" {
                    // these are manually added steps

                    steps += result.quantity.doubleValueForUnit(HKUnit.countUnit())
                }
                else{
                    // these are auto detected steps which we do not want from HKSampleQuery
                }
            }
            completion(steps, error)

            return
        } else {
            // mostly not executed
            completion(steps, error)
        }
    }
    executeQuery(query)
}

以下是如何调用它

 MyHealthStore.sharedHealthStore.TodayTotalSteps { (stepRetrieved) in 
     print(stepRetrieved)
 }

我希望它有所帮助,如果您发现任何困难,请告诉我。

答案 1 :(得分:0)

以下是HKStatisticsCollectionQuery

document中提供的代码
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *interval = [[NSDateComponents alloc] init];
interval.day = 7;

// Set the anchor date to Monday at 3:00 a.m.
NSDateComponents *anchorComponents =
[calendar components:NSCalendarUnitDay | NSCalendarUnitMonth |
 NSCalendarUnitYear | NSCalendarUnitWeekday fromDate:[NSDate date]];

NSInteger offset = (7 + anchorComponents.weekday - 2) % 7;
anchorComponents.day -= offset;
anchorComponents.hour = 3;

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);
        abort();
    }

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

    // Plot the weekly step counts over the past 3 months
    [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]];

             // Call a custom method to plot each data point.
             [self plotWeeklyStepCount:value forDate:date];
         }

     }];
};

[self.healthStore executeQuery:query];

在给定的代码中,提到了2个日期

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

根据您的要求更改startDate和endDate。