When do the HKWorkoutBuilder.finishWorkout() returns nil ?

I use the following code :

do {
  ...
        Logger.health.info(c: .saveWorkout, "Ending collection.")
      try await builder.endCollection(at: workout.end)

      Logger.health.info(c: .saveWorkout, "Finishing workout.")
      let hkFinishedWorkout = try await builder.finishWorkout()

      guard let hkworkout = hkFinishedWorkout else {
        Logger.health.error(c: .saveWorkout, "Error finishing workout. Returned workout is nil!")
        return false
      }
     ...

} catch {
      Logger.health.error(c: .saveWorkout, "Failed to save workout: \(String(describing: error))")
      return false
}

This code sometimes behave correctly, but it also happen to log "Error finishing workout. Returned workout is nil!" which indicates that the builder.finishWorkout() returned nil without throwing an error.

Notes:

  • There is a workout session running in parallel on the AppleWatch.
  • The workout is correctly saved, but all the location information is missing as the route builder needs the workout to be saved.

My question is when do finishWorkout()returns nil without throwing an error ?

Answered by Frameworks Engineer in 696894022

If the device is locked, finishing a workout will succeed but will not be able to return the HKWorkout object. You'll be able to query for that object once the device unlocks again.

Accepted Answer

If the device is locked, finishing a workout will succeed but will not be able to return the HKWorkout object. You'll be able to query for that object once the device unlocks again.

When do the HKWorkoutBuilder.finishWorkout() returns nil ?
 
 
Q