Search code examples
ioshealthkithkhealthstorehksamplequery

Getting most recent BMI value from HKHealthStore


I want to get the users most recent BMI reading from my instance of HKHealthStore. As of right now I am doing it as follows but it doesn't seem right. Is there a way to get an actual numerical value for BMI instead of a countUnit (HKUnit)?

HKQuantityType *bodyMassIndexType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierBodyMassIndex];

    HKSampleQuery *bmiSampleQuery = [[HKSampleQuery alloc] initWithSampleType:bodyMassIndexType predicate:nil limit:1 sortDescriptors:nil resultsHandler:^(HKSampleQuery *query, NSArray *results, NSError *error) {

        if (results.count == 0)
        {
            //No results
        }
        else
        {
            if (!error)
            {
                NSString *bmiString = [NSString stringWithFormat:@"%@", [[results firstObject] quantity]];
                NSString *parsedBMIString = [bmiString stringByReplacingOccurrencesOfString:@" count" withString:@""];
                NSLog(@"%f", [parsedBMIString floatValue]);
            }
        }
    }];

    [self.store executeQuery:bmiSampleQuery];

Solution

  • The sample returns an array, so you can simply pull out the first object from the array and then convert it's value to a double for handling.

    HKQuantitySample *sample = [results firstObject];
    int i = [sample.quantity doubleValueForUnit:[HKUnit countUnit]];
    NSLog(@"%i",i);