Reputation: 551
I'm trying to get steps count for each hour and for this I do:
func retrieveSteps(completion: @escaping (_ stepsCount: Double) -> Void) {
let stepsCount = HKQuantityType.quantityType(forIdentifier: .stepCount)
let date = Date()
let calendar = Calendar(identifier: .gregorian)
let newDate = calendar.startOfDay(for: date)
let predicate = HKQuery.predicateForSamples(withStart: newDate, end: date, options: [.strictStartDate])
var interval = DateComponents()
interval.hour = 1
let query = HKStatisticsCollectionQuery(quantityType: stepsCount!, quantitySamplePredicate: predicate, options: [.cumulativeSum], anchorDate: newDate, intervalComponents: interval)
query.initialResultsHandler = { query, result, error in
if let stats = result {
stats.enumerateStatistics(from: newDate, to: date) { statistics, _ in
if let quantity = statistics.sumQuantity() {
let steps = quantity.doubleValue(for: HKUnit.count())
print("Steps: \(steps) for: \(statistics.endDate)")
completion(steps)
}
}
}
}
HKHealthStore().execute(query)
}
And when I execute it I get incorrect date values. For example:
Steps: 28.3782023430627 for: 2017-10-22 10:00:00 +0000
but on Health app it shows time 11:58
. Why I'm getting 10:00
? And how can I improve it?
Upvotes: 0
Views: 642
Reputation: 7353
The statistics object you get back from HKStatisticsCollectionQuery
represents a range of time the size of the interval components you provided, rather than the date of specific samples that fall inside that time range. If you want to find the date of the most recent step count sample in HealthKit, you should use an HKSampleQuery
.
Upvotes: 1