0

I'm trying to start a workout session in Apple Watch with session.startActivity but the state remains NotStarted (1). even though, it seems like the workout did start since my app runs in the background and also my Watch shows the workout symbol. later, when I try to stop the workout with session.end, I get this error:

"Unable to transition to the desired state from the NotStarted(1) state (event 6). Allowed transitions from the current state are: {
7 = "<error(7): NotStarted(1) -> Ended(3)>";
1 = "<prepare(1): NotStarted(1) -> Prepared(5)>";
2 = "<start(2): NotStarted(1) -> Running(2)>";" 

according to the error message, I should be able to perform this since I'm in NotStarted mode (error 7). can someone please help? I'm lost.... here is my code:

var session: HKWorkoutSession? = nil
var builder: HKLiveWorkoutBuilder!

func workout(state: String) {
    
    do {
        session = try HKWorkoutSession(healthStore: healthStore, configuration: configuration)
        builder = session?.associatedWorkoutBuilder()
    } catch {
        print("error with workout session")
        return
    }
    
    session?.delegate = self
    builder.delegate = self
    builder.dataSource = HKLiveWorkoutDataSource(healthStore: healthStore, workoutConfiguration: configuration)
    
    if (state == "start") {
        session?.startActivity(with: Date())
        builder.beginCollection(withStart: Date()) { (success, error) in
            guard success else {
                print("error with builder")
                return
            }
        }
    } else if (state == "end") {
        session?.end()
    }
}

    func workoutSession(_ workoutSession: HKWorkoutSession, didChangeTo toState:     HKWorkoutSessionState, from fromState: HKWorkoutSessionState, date: Date) {
    print("from state: \(fromState.rawValue)")
    print("to state: \(toState.rawValue)")
    if toState == .ended {
        builder.endCollection(withEnd: Date()) { (success, error) in
            self.builder.finishWorkout { (workout, error) in
            }
        }
    }
    
}
Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
Yarden
  • 11
  • 3

1 Answers1

1

"session" - are you sure it's the same object as the one that started the workout?

After you start, when you call workout(state: "stop") later, you do this:

func workout(state: String) {
    
    do {
        session = try HKWorkoutSession(healthStore: healthStore, configuration: configuration)

And that will overwrite your existing session object, so it's a different session you're trying to stop, that session never started, so it can't stop.

Shadowrun
  • 3,572
  • 1
  • 15
  • 13