WatchOS 9.1 / HealthKit error “Unable to transition to desired state”

I’ve got a WatchOS app in the App Store, but since WatchOS 9.1 it’s no longer updating workoutManager.heartRate nor is it saving workout data to Apple’s Health store. Curiously, workoutManager.builder?.elapsedTime, is still correct.

No errors are thrown while executing these lines of code:

  session = try HKWorkoutSession(healthStore: healthStore, configuration: configuration)
  builder = session?.associatedWorkoutBuilder()

… and shortly after this completion block executes,

  session?.startActivity(with: startDate)
  builder?.beginCollection(withStart: startDate) { (success, error) in
      print("WorkoutMgr.startWorkout() - The workout has started.")
  }

… I get the following error messages in my log:

2022-09-28 18:15:01.380071-0500 AppName WatchKit Extension[1240:609337] [workouts] HKLiveWorkoutBuilder_6311 [B194]: (#w0) Failed to update target construction state: Error Domain=com.apple.healthkit Code=3 "Unable to transition to the desired state from the Error(6) state (event 1). Allowed transitions from the current state are: {

}" UserInfo={HKErrorParameter=@"", NSLocalizedDescription=Unable to transition to the desired state from the Error(6) state (event 1). Allowed transitions from the current state are: {

}, HKErrorClass=HKStateMachine, HKErrorSelector=_handleEvent:date:error:completion:}

No developer.apple.com nor StackOverflow.com searches have resulted in any relevant discussions.

Any help will be GREATLY appreciated!

Answered by CryptoKoa in 731623022

Well, I finally figured it out myself. Turns out that somewhere around WatchOS 9 RC, the place where I had been calling workoutManager.requestingAuthorization() (ie, I was calling it from ContentView.onChange(of:scenePhase) ) became no longer valid, and I had to instead call .requestingAuthorization() from within the .onAppear() of the view which actually starts the workout.

I’ve not seen any documentation that relates to where in my code base I need to call the workout.requestingAuthorization(), and the fact that the workoutManager.elapsedTime was functioning gave me some headaches, but all’s well now.

Accepted Answer

Well, I finally figured it out myself. Turns out that somewhere around WatchOS 9 RC, the place where I had been calling workoutManager.requestingAuthorization() (ie, I was calling it from ContentView.onChange(of:scenePhase) ) became no longer valid, and I had to instead call .requestingAuthorization() from within the .onAppear() of the view which actually starts the workout.

I’ve not seen any documentation that relates to where in my code base I need to call the workout.requestingAuthorization(), and the fact that the workoutManager.elapsedTime was functioning gave me some headaches, but all’s well now.

WatchOS 9.1 / HealthKit error “Unable to transition to desired state”
 
 
Q