Hi there, I'm trying to read workouts from a WatchOS App. Unfortunately, the returned workouts are always empty.
This is how it's currently implemented:
func fetchWorkouts(limit: WorkoutLimit) async throws -> [HKWorkout] {
let activityType = PulseConfiguration.activityType
// 1. Get all workouts with the configured activity type.
let walkingPredictate = HKQuery.predicateForWorkouts(with: activityType)
// 2. Get all workouts that only came from this app.
let sourcePredicate = HKQuery.predicateForObjects(from: .default())
// 3. Combine the predicates into a single predicate.
let compound = NSCompoundPredicate(andPredicateWithSubpredicates:
[walkingPredictate, sourcePredicate])
let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierEndDate, ascending: false)
typealias WorkoutsContinuation = CheckedContinuation<[HKWorkout], Error>
return try await withCheckedThrowingContinuation { (continuation: WorkoutsContinuation) in
let query = HKSampleQuery(
sampleType: .workoutType(),
predicate: compound,
limit: limit.count,
sortDescriptors: [sortDescriptor]
) { _, samples, error in
guard let samples = samples as? [HKWorkout], error == nil else {
if let error = error {
continuation.resume(throwing: error)
}
return
}
continuation.resume(returning: samples)
}
healthStore.execute(query)
}
}
I noticed that the HKSource
returned by .default
(WatchOS) is different than the source associated to the saved workouts (Which contains the bundle identifier from the iPhone App).
Is there some other way to access the workouts from the WatchOS App?
Thanks in advance. Josh.