Skip to content

Instantly share code, notes, and snippets.

@jault3 jault3/PopulateWeight.m
Last active Aug 29, 2015

Embed
What would you like to do?
Populate Weight from HealthKit
HKQuantityType *weightType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierBodyMass];
// Since we are interested in retrieving the user's latest sample
// we sort the samples in descending order by end date
// and set the limit to 1
// We are not filtering the data, and so the predicate is set to nil.
NSSortDescriptor *timeSortDescriptor = [[NSSortDescriptor alloc] initWithKey:HKSampleSortIdentifierEndDate ascending:NO];
// construct the query & since we are not filtering the data the predicate is set to nil
HKSampleQuery *query = [[HKSampleQuery alloc] initWithSampleType:weightType predicate:nil limit:1 sortDescriptors:@[timeSortDescriptor] resultsHandler:^(HKSampleQuery *query, NSArray *results, NSError *error) {
// if there is a data point, dispatch to the main queue
if (results) {
dispatch_async(dispatch_get_main_queue(), ^{
HKQuantitySample *quantitySample = results.firstObject;
// pull out the quantity from the sample
HKQuantity *quantity = quantitySample.quantity;
HKUnit *weightUnit = [HKUnit poundUnit];
double usersWeight = [quantity doubleValueForUnit:weightUnit];
_txtWeight.text = [NSString stringWithFormat:@"%@ lbs", [NSNumberFormatter localizedStringFromNumber:@(usersWeight) numberStyle:NSNumberFormatterNoStyle]];
});
}
}];
// do not forget to execute the query after its constructed
[_healthStore executeQuery:query];
@zhaomizhi

This comment has been minimized.

Copy link

commented Apr 27, 2015

Hi, I follow almost all code from you post. However, my program did not really "execute" the query. I write some NSLog (before if (results)) and debug to check and found that it never really run the code in query block.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.