I've asked this question on Apple's Developer Forum 6 months ago and not one reply. So I'm hoping you guys can do better lol
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.
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
CodePudding user response:
Ok, so i'm going to mark this as solved, even though some questions remain. After @TyR pointed out my mistake of using int
data type and correcting that, I can confirm that the data that gets reported via the HealthKit API corresponds exactly to the data reported by the Health App if I look at the Data Sources section and choose my Apple Watch Data Source and manually add up all of the samples it has collected. So, I'm confident that my data is correct since it matches the values in Data Sources. However, the value that's reported in the overview section in the Health App is different from the data in the Data Sources section as well as those reported via the HealthKit API. Apple must be doing some sort of correction algorithm or grabbing only relevant samples when crossing day/night boundaries. I am satisfied now, after fixing that int
error, that i am getting the appropriate data. Thank you so much!