Hello!
HealthKit is hard :)
Context: I'm building an app to keep track of mileage the user ran in their shoes. The user can manually log workouts, but I'm working on finishing up HealthKit integration so the user just has to log a workout in Health however they see fit and the app will find it.
HealthKit is connected and mostly working with one big exception.
Here is the issue I'm running into: If the user completes a workout and the app in either the background or foreground, the workout cannot be found until the user quits/reboots the app.
The below function I believe is the culprit. Specifically, the HKSampleQuery does not find workouts logged since the app launched.
Is there a way to find new workouts without quitting/restarting the app?
func asyncGetWorkouts(start: Date, end: Date) async -> [HKWorkout]? {
let store = HKHealthStore()
let walkingPredicate = HKQuery.predicateForWorkouts(with: .walking)
let timePredicate = HKQuery.predicateForSamples(withStart: start, end: end, options: .strictStartDate)
let walkingCompound = NSCompoundPredicate(andPredicateWithSubpredicates:
[walkingPredicate, timePredicate])
let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierEndDate, ascending: false)
func startQuery() async -> [HKWorkout] {
let group = DispatchGroup()
group.enter()
var output: [HKWorkout] = []
let query = HKSampleQuery(sampleType: .workoutType(), predicate: walkingCompound, limit: 0, sortDescriptors: [sortDescriptor]) { (query, samples, error) in
guard let samples = samples as? [HKWorkout], error == nil else {
return
}
output = samples
group.leave()
}
store.execute(query)
group.wait()
return output
}
return await startQuery()
}