Hi, i'm trying to get the number of step counts a person has taken. I decided to pull the data from health kit and the number of steps are incorrect. Come to find out apple health recommends an app called pedometer++ for the number of steps counted and after testing I realized that they are getting the correct number of steps a person is taking. How can I pull the correct number of steps a person has taken? I want to be able to merge the data from watch and phone to make sure we are getting the correct number of steps but not double counting the steps either.
any guidance on this would be appreciated!
Here's the code snippet that i'm using right now:
permissions: {
read: [AppleHealthKit.Constants.Permissions.StepCount],
write: [],
},
};
AppleHealthKit.initHealthKit(permissions, error => {
if (error) {
console.log('Error initializing HealthKit: ', error);
return;
} else {
dispatch(setAllowHealthKit(true));
getHealthKitData();
console.log('HealthKit initialized successfully');
}
});
const getHealthKitData = async () => {
try {
const today = new Date();
const options = {
startDate: new Date(today.setHours(0, 0, 0, 0)).toISOString(),
endDate: new Date().toISOString(),
};
const steps = await new Promise((resolve, reject) => {
AppleHealthKit.getStepCount(options, (error, results) => {
if (error) reject(error);
resolve(results?.value);
});
});
setStepsCount(steps);
} catch (error) {
console.error('Error fetching HealthKit data:', error);
}
};
HealthKit allows multiple sources to produce conflicting data. If you query for raw data (samples and series) you'll see all of it. If you query for aggregate data (statistics, summaries) using HKStatisticsQuery or KStatisticsCollectionQuery, as @doublep mentioned, HealthKit will dedupe for you.
In your case, you can consider using HKStatisticsQuery
, which should gives you the right steps, as shown below:
let sampleType = HKSampleType.quantityType(forIdentifier: .stepCount)!
let predicate = HKQuery.predicateForSamples(withStart: Date(timeIntervalSinceNow: -24 * 60 * 60), end: Date())
let statisticsQuery = HKStatisticsQuery(quantityType: sampleType,
quantitySamplePredicate: predicate,
options: [.cumulativeSum]) { query, statistics, error in
if let error = error {
print("Failed to run statistics query: \(error)")
return
}
if let quantity = statistics?.sumQuantity() {
let stepCount = quantity.doubleValue(for: .count())
print("Step count = \(stepCount)")
}
}
healthStore.execute(statisticsQuery)
Best,
——
Ziqiao Chen
Worldwide Developer Relations.