I want to fetch step count from Health app on hourly basis.
But statistics.sumQuantity() in below code always returns nil value.
Note : As I want step count on hourly basis within same day so I am passing startDate and endDate both are same.
In below code output is always, No Step quantity.
let predicate = HKQuery.predicateForSamples(withStart: startDate, end: endDate, options:[ .strictStartDate])
var interval = DateComponents()
interval.hour = 1
let query = HKStatisticsCollectionQuery(quantityType: sampleType,
quantitySamplePredicate: predicate,
options: [.cumulativeSum],
anchorDate: startDate,
intervalComponents: interval)
query.initialResultsHandler = { query, statsCollection, error in
if error != nil {
completion(nil, error)
return
}
var totalSum = 0.0
if let myResults = statsCollection { myResults.enumerateStatistics(from: startDate, to: startDate) { statistics, stop in
if let quantity = statistics.sumQuantity() {
let date = statistics.startDate
let steps = quantity.doubleValue(for: HKUnit.count())
totalSum = totalSum + steps
} else {
print("No step quantity")
let steps = 0.0
let date = statistics.startDate
}
}
}
DispatchQueue.main.async {
}
}
self.healthStore.execute(query)