we are trying to retrieve the daily step count and calories burn data from Health using HealthKit. The methods been used were:
stepCount = HKSampleType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount)
caloriesBurn = HKSampleType.quantityType(forIdentifier: .activeEnergyBurned)
And, query executed using,
HKSampleQuery(sampleType: <stepCount or caloriesBurn>, predicate: last24hPredicate, limit: HKObjectQueryNoLimit, sortDescriptors: nil)
But, depend upon the situations, we are facing data inconsistent issues while retrieving using HealthKit.
Happy situation: If we depend only on iPhone while doing the daily activities and data then retrieve using HealthKit into our app, both the step count and calories burn data are showing as same as in Health app.
Sad situation: If we use Apple Watch while doing daily activities, both the step count and calories burn won't get correctly into our app, always data mismatched.
As most of the clients are using gadgets to track their activities, data mismatched between Health app and ours, won't be acceptable.
Please suggest better solutions to overcome the issues.
Attached some screenshots of Health, Fitness and ours apps to show the data mismatched situations.
We need to show exactly same value of all parameters form Health app to our own app, especially focus on step count, calories burn.
I used HKStatisticsQuery for this purpose and solved the issue.
let now = Date()
let startOfDay = Calendar.current.startOfDay(for: now)
let predicate = HKQuery.predicateForSamples(withStart: startOfDay, end: now, options: .strictStartDate)
let query = HKStatisticsQuery(quantityType: energyType, quantitySamplePredicate: predicate, options: .cumulativeSum) { (_, statisticsOrNil, _) in
guard let statistics = statisticsOrNil else {
return
}
// perform further operation
}