How to access workouts from HealthKit on WatchOS?

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.

Replies

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).

Could you file a feedback assistant report for this?

The watch contains a subset of data from the phone (approx last 7 days) so you won't be able to see workouts older than that. If the source bundle identifier is the cause then you could query for all workouts and then manually filter based on the source to work around the issue. But please do file a report so we can take a look.