【问题标题】:can't start workout session with HKWorkoutSession无法使用 HKWorkoutSession 开始锻炼课程
【发布时间】:2021-05-14 14:19:34
【问题描述】:

我正在尝试使用 session.startActivity 在 Apple Watch 中开始锻炼,但状态仍为 NotStarted (1)。 尽管如此,似乎锻炼确实开始了,因为我的应用程序在后台运行,而且我的手表也显示了锻炼符号。 后来,当我尝试使用 session.end 停止锻炼时,我收到此错误:

"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)>";" 

根据错误消息,我应该能够执行此操作,因为我处于未启动模式(错误 7)。 有人可以帮忙吗?我迷路了.... 这是我的代码:

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
            }
        }
    }
    
}

【问题讨论】:

    标签: swift apple-watch healthkit watchos


    【解决方案1】:

    “会话” - 您确定它与开始锻炼的对象是同一个对象吗?

    开始后,当您稍后调用锻炼(状态:“停止”)时,您会这样做:

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

    这将覆盖您现有的会话对象,因此您尝试停止的是另一个会话,该会话从未启动,因此无法停止。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-23
      • 1970-01-01
      相关资源
      最近更新 更多