Skip to content

Instantly share code, notes, and snippets.

@max6363
Created May 8, 2018 20:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save max6363/319a726b7644b00ea13fb63b0a069239 to your computer and use it in GitHub Desktop.
Save max6363/319a726b7644b00ea13fb63b0a069239 to your computer and use it in GitHub Desktop.
- (NSDate *)dateFromString:(NSString *)dateString
{
NSString *dt_format_string = @"yyyy-MM-dd'T'HH:mm:ss";
NSDateFormatter *dtFormat = [[NSDateFormatter alloc]init];
[dtFormat setDateFormat:dt_format_string];
NSCalendar *gregorian = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian];
dtFormat.calendar = gregorian;
NSLocale *enUSPOSIXLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
dtFormat.locale = enUSPOSIXLocale;
NSDate *date = [dtFormat dateFromString:dateString];
return date;
}
/**
Read Cycling Distance
*/
- (void)readCyclingDistanceWithFinishBlock:(void (^)(NSError *error, NSNumber *value))finishBlock
{
// start date
NSDate *startDate = [self dateFromString:@"2018-05-08T00:00:00"];
// end date
NSDate *endDate = [self dateFromString:@"2018-05-08T23:59:59"];
// Sample type
HKSampleType *sampleCyclingDistance = [HKSampleType quantityTypeForIdentifier:HKQuantityTypeIdentifierDistanceCycling];
// Predicate
NSPredicate *predicate = [HKQuery predicateForSamplesWithStartDate:startDate
endDate:endDate
options:HKQueryOptionStrictStartDate];
// valud
__block float dailyValue = 0;
// query
HKSampleQuery *query = [[HKSampleQuery alloc] initWithSampleType: sampleCyclingDistance
predicate: predicate
limit: 0
sortDescriptors: nil
resultsHandler:^(HKSampleQuery *query, NSArray* results, NSError *error){
dispatch_sync(dispatch_get_main_queue(), ^{
if (error) {
NSLog(@"error");
finishBlock(error, nil);
} else {
for(HKQuantitySample *samples in results)
{
dailyValue += [[samples quantity] doubleValueForUnit:[HKUnit mileUnit]];
}
finishBlock(nil, @(dailyValue));
}
});
}
];
// execute query
[self.healthStore executeQuery:query];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment