如何解决无法使用 HKWorkoutSession 开始锻炼
我正在尝试使用 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)>";"
根据错误消息,我应该能够执行此操作,因为我处于 NotStarted 模式(错误 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
}
}
}
}
解决方法
“会话” - 您确定它与开始锻炼的对象是同一对象吗?
开始后,当你稍后调用锻炼(状态:“停止”)时,你这样做:
func workout(state: String) {
do {
session = try HKWorkoutSession(healthStore: healthStore,configuration: configuration)
这将覆盖您现有的会话对象,因此您要停止的是另一个会话,该会话从未启动,因此无法停止。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。