I have this function that has a completion handler that is to be returned after the task is finished, but from the output I am getting, it shows that the completion handler is being considered completed and returned before the task is done.
Function being called:
private func getSteps(completion: (Int) -> ()) {
var val: Int = 0
guard let sampleType = HKObjectType.quantityType(forIdentifier: .stepCount) else { return }
let startDate = Calendar.current.startOfDay(for: Date())
let predicate = HKQuery.predicateForSamples(withStart: startDate, end: Date(), options: .strictEndDate)
var interval = DateComponents()
interval.day = 1
let query = HKStatisticsCollectionQuery(quantityType: sampleType, quantitySamplePredicate: predicate, options: [.cumulativeSum], anchorDate: startDate, intervalComponents: interval)
query.initialResultsHandler = { query,result,error in
if let myresult = result {
myresult.enumerateStatistics(from: startDate, to: Date()) { (statistic, value) in
if let count = statistic.sumQuantity() {
val = Int(count.doubleValue(for: HKUnit.count()))
}
}
}
}
healthStore.execute(query)
completion(val)
}
When I print the completion handler of the function, it prints 0
instead of Int(count.doubleValue(for: HKUnit.count()))
which val was set to inside the function. Any input on why I am getting 0
instead of the set val would be greatly appreciated!