【发布时间】: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