I have been trying to query HealthKit for the number of steps on my phone. Here is what I have tried:
let endDate = NSDate()
let startDate = NSCalendar.currentCalendar().dateByAddingUnit(.Day, value: -1, toDate: endDate, options: [])
let sampleType = HKSampleType.quantityTypeForIdentifier(HKQuantityTypeIdentifierStepCount)
let predicate = HKQuery.predicateForSamplesWithStartDate(startDate, endDate: endDate, options: .None)
let query = HKSampleQuery(sampleType: sampleType!, predicate: predicate, limit: 0, sortDescriptors: nil, resultsHandler: { (query, results, error) in
if results == nil {
print("There was an error running the query: \(error)")
return
}
dispatch_async(dispatch_get_main_queue()) {
//print(results)
dispatch_async(dispatch_get_main_queue()) {
let steps = results as! [HKQuantitySample]
print(steps.count)
for step in steps {
self.stepsLabel.text = String(step.quantity)
}
}
}
})
self.healthKitStore.executeQuery(query)
As a result of this, stepsLabel
is now displaying "296 count". However, I have much more steps than that. I do not know why it is not updating correctly. I have looked at this post and this one as well. However, I have not understood the answers well. How should I make sure that the query is updating properly? Thanks for your help.
You are displaying only the quantity of the last sample.
Lets assume you have 100 samples. You're updating your label 100 times with a different quantity value and what you are seeing is the quantity value of the last update.
To see the sum of all selected samples, you have to sum up all quantity values of all (relevant) samples.