watchkithealthkitwatchos-5

watchOS 5: HKLiveWorkoutBuilder, HKWorkoutRouteBuilder and Workout Distance


I am using HKLiveWorkoutBuilder & HKWorkoutRouteBuilder to track a workout on Apple Watch.

when calling:

[workoutBuilder finishWorkoutWithCompletion:^(HKWorkout * _Nullable workout, NSError * _Nullable error) {

}];

The returned workout object does not include the distance that the user travelled:

(lldb) po workout.totalDistance
nil

However the route is saved correctly.

Given that .totalDistance is read only, how should I set the distance of the workout in watchOS 5?

enter image description here

enter image description here


Solution

  • There are two parts to the answer here.

    To get it working for walking or running you can use the following code:

    workoutBuilder?.beginCollection(withStart: Date(), completion: { (success, error) in
        guard success == true else {
            #warning ("deal with failure")
            return
        }
    
        workoutBuilder?.dataSource = HKLiveWorkoutDataSource(healthStore:self.healthStore, workoutConfiguration: self.workoutConfig)
    
        // 👇👇 this is the important bit 👇👇
        workoutBuilder?.dataSource?.enableCollection(for: HKQuantityType.quantityType(forIdentifier: .distanceWalkingRunning)!, predicate: nil)
    
        workoutBuilder?.dataSource?.enableCollection(for: HKQuantityType.quantityType(forIdentifier: .heartRate)!, predicate: nil)
        workoutBuilder?.dataSource?.enableCollection(for: HKQuantityType.quantityType(forIdentifier: .activeEnergyBurned)!, predicate: nil)
    
    })
    

    You can adapt this for swimming and skiing.

    There is currently no way to use workout builder to get distance on other types of outdoor activity, eg rowing.

    --

    Radar/Feedback details for if you want to Copy & Paste

    Feedback No: FB5714600

    Title: Support distance tracking for more exercise types

    Body:

    Currently live workout builder only includes support for tracking distance for the following types: - walking or running distance - skiing - swimming

    I see two options. The best would be to allow something like:

    workoutBuilder?.dataSource?.enableCollection(for: HKQuantityType.quantityType(forIdentifier: .distancePaddling)!, predicate: nil)
    

    Another option would be to allow workouts to be mutable so that the distance could be added retrospectively.

    I'm happy to provide further input if required. Our users love the Apple Watch, but it is frustrating for them that they can't store the distance of their paddle workouts in Health.