Last active
August 29, 2015 14:06
-
-
Save jault3/432330035ed51e76c05e to your computer and use it in GitHub Desktop.
Populate Height from HealthKit
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
HKQuantityType *heightType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierHeight]; | |
// 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 | |
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:heightType 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 *heightUnit = [HKUnit inchUnit]; | |
double usersHeight = [quantity doubleValueForUnit:heightUnit]; | |
_txtHeight.text = [NSString stringWithFormat:@"%@ in", [NSNumberFormatter localizedStringFromNumber:@(usersHeight) numberStyle:NSNumberFormatterNoStyle]]; | |
}); | |
} | |
}]; | |
// do not forget to execute the query after its constructed | |
[_healthStore executeQuery:query]; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment