I am trying to make my app show the total of steps I have done today. According to by Health-Kit app on my phone I have done 6 steps, but the app tells me 0. This is the full code I am using:
import UIKit
import HealthKit
class ViewController: UIViewController {
@IBOutlet weak var stepsLabel: UILabel!
let healthStore = HKHealthStore()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
getTodaysSteps { (count) in
DispatchQueue.main.async {
self.stepsLabel.text = count.description
print("DONE: \(count)")
}
}
}
func getTodaysSteps(completion: @escaping (Double) -> Void) {
let stepsQuantityType = HKQuantityType.quantityType(forIdentifier: .stepCount)!
let now = Date()
let startOfDay = Calendar.current.startOfDay(for: now)
let predicate = HKQuery.predicateForSamples(withStart: startOfDay, end: now, options: .strictStartDate)
let query = HKStatisticsQuery(quantityType: stepsQuantityType, quantitySamplePredicate: predicate, options: .cumulativeSum) { _, result, _ in
guard let result = result, let sum = result.sumQuantity() else {
completion(0.0)
return
}
completion(sum.doubleValue(for: HKUnit.count()))
}
healthStore.execute(query)
}
}
Is there anything I have missed here? Code from: https://stackoverflow.com/a/44111542/10660554