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.