Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save bellebethcooper/dd6055c9221840705d51470d88f1c308 to your computer and use it in GitHub Desktop.
Save bellebethcooper/dd6055c9221840705d51470d88f1c308 to your computer and use it in GitHub Desktop.
- (void)readAverageValueFromHealthKitWithIdentifier:(HKQuantityType *)identifier
unit:(HKUnit *)unit
options:(HKStatisticsOptions)options
startDate:(NSDate *)startDate
andEndDate:(NSDate *)endDate
completionBlock:(void (^)(NSError *error, NSDictionary *dict))completionBlock {
// HKQueryOptionStrictStartDate requires any samples HealthKit
// returns to have start dates that fall within the period
// between the start and end dates we pass in here
NSPredicate *predicate = [HKQuery predicateForSamplesWithStartDate:startDate
endDate:endDate
options:HKQueryOptionStrictStartDate];
// HKStatisticsQuery is used for calculating minimums, maximums, and averages
// We want an average of weight for each day
// in case the user weighs in multiple times so the options parameter
// will just be HKStatisticsOptionDiscreteAverage
// The identifier in this case is HKQuantityTypeIdentifierBodyMass
HKStatisticsQuery *statsQuery = [[HKStatisticsQuery alloc] initWithQuantityType:identifier
quantitySamplePredicate:predicate
options:options
completionHandler:^(HKStatisticsQuery * _Nonnull query, HKStatistics * _Nullable result, NSError * _Nullable error) {
if (error) {
// handle error and return
}
// try to get value from the result
// if no value, return
// If there is a value, format it:
// Turn the startDate (An NSDate) into a string like "2018-01-15"
// Create a dictionary that looks like this:
{ "2018-01-15": 90.5}
// These dictionaries will be combined by the caller of this method
// so a whole bunch of dates and values can be sent to the API at once
// call completion block here and return the dictionary we just created
}];
// Execute the query
[healthStore executeQuery:statsQuery];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment