Patrick
Patrick

Reputation: 302

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];

Upvotes: 1

Views: 449

Answers (1)

Lvia
Lvia

Reputation: 36

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);

Upvotes: 2

Related Questions