I'm using Apple's HealthKit API in a WatchOS app to retrieve energy metrics such as Active Energy and Basal Energy burned. The issue I have is in getting accurate data. Apple's Health App on the iPhone is showing one value, and the data that is returned via HealthKit is another. Sometimes the data is the same, and other times there can be a delta of 500-600 calories. Here is a sample of my code showing how I use the HealthKit API to retrieve the energy data.
Calling this code on WatchOS and iOS both result in the same issues as outlined above
Code Block NSDate* StartOfDay = [[NSCalendar currentCalendar] startOfDayForDate:[NSDate now]]; NSDateComponents* Components = [[NSDateComponents alloc] init]; Components.day = 1; NSDate* EndOfDay = [[NSCalendar currentCalendar] dateByAddingComponents:Components toDate:StartOfDay options:NSCalendarWrapComponents]; HKSampleType* SampleType = [HKSampleType quantityTypeForIdentifier:HKQuantityTypeIdentifierBasalEnergyBurned]; NSPredicate *Predicate = [HKQuery predicateForSamplesWithStartDate:StartOfDay endDate:EndOfDay options:HKQueryOptionNone]; NSSortDescriptor *SortDescriptor = [NSSortDescriptor sortDescriptorWithKey:HKSampleSortIdentifierStartDate ascending:YES]; HKSampleQuery* SampleQuery = [[HKSampleQuery alloc] initWithSampleType:SampleType predicate:Predicate limit:HKObjectQueryNoLimit sortDescriptors:@[SortDescriptor] resultsHandler:^(HKSampleQuery * _Nonnull query, NSArray<__kindof HKSample *> * _Nullable results, NSError * _Nullable error) { if (!error && results) { int BasalCalBurned = 0; for (HKQuantitySample *samples in results) { BasalCalBurned += [[samples quantity] doubleValueForUnit:[HKUnit largeCalorieUnit]]; } } }
Calling this code on WatchOS and iOS both result in the same issues as outlined above