swift - 为什么我的 HKWorkoutSession(通常)没有结束?

标签 swift watchkit apple-watch healthkit

我正在为 Apple Watch 开发一个非常简单的锻炼应用程序。它使用 Health Kit 开始和结束锻炼,我唯一的问题是,当我尝试结束锻炼时,它通常不会结束 session ,我收到此错误

2020-07-22 12:27:46.547720-0700 5k WatchKit Extension[25774:944527] [workouts] <HKWorkoutSession:0x80156310 A54AF52C-8B08-4BAD-A28C-03D8E54044B5 ended>: Failed to end: Error Domain=com.apple.healthkit Code=3 "Unable to transition to the desired state from the Ended(3) state (event 6). Allowed transitions from the current state are: {
    7 = "<error(7): Ended(3) -> Ended(3)>";
}" UserInfo={NSLocalizedDescription=Unable to transition to the desired state from the Ended(3) state (event 6). Allowed transitions from the current state are: {
    7 = "<error(7): Ended(3) -> Ended(3)>";
}}

我什至不确定从哪里开始从这些信息中寻找问题,也不知道这意味着什么。此外,通常在第 4 次或第 5 次尝试时,它实际上会结束锻炼。

最佳答案

可能的原因是结束锻炼类(class)和锻炼构建器数据收集的顺序错误。

如果您的代码看起来与此类似,您将收到错误:

session.end()
        
builder.endCollection(withEnd: Date()) { (success, error) in
 builder.finishWorkout { (workout, error) in
// do something
 }
}

session 尚未结束,但代码立即尝试结束构建器的 session 。

在 Apple 的示例中 ( https://developer.apple.com/documentation/healthkit/workouts_and_activity_rings/speedysloth_creating_a_workout ) 是通过代表完成锻炼的正确方法:

session.delegate = self
.....
func endWorkout() {
        // End the workout session.
        session.end()
}
....
extension WorkoutManager: HKWorkoutSessionDelegate {
    func workoutSession(_ workoutSession: HKWorkoutSession, didChangeTo toState: HKWorkoutSessionState,
                        from fromState: HKWorkoutSessionState, date: Date) {
        // Wait for the session to transition states before ending the builder.
        /// - Tag: SaveWorkout
        if toState == .ended {
            print("The workout has now ended.")
            builder.endCollection(withEnd: Date()) { (success, error) in
                self.builder.finishWorkout { (workout, error) in
                    // Optionally display a workout summary to the user.
                    self.resetWorkout()
                }
            }
        }
    }
    
    func workoutSession(_ workoutSession: HKWorkoutSession, didFailWithError error: Error) {
        
    }
}

关于swift - 为什么我的 HKWorkoutSession(通常)没有结束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63041909/

相关文章:

ios - 二元运算符 '>=' 不能应用于类型 'Any' 和 'Int' 的操作数

ios - 无法覆盖在另一个模块 swift 的类扩展中声明的打开方法

nstimer - Apple Watch 显示器 sleep 暂停 NSTimer,但 WKInterfaceTimer 一直倒计时

ios - 自定义字体在 WatchKit InterfaceFile 中显示自定义(未安装)

ios - 在 iPhone 和 Apple Watch 之间发送数据时减少延迟的策略?

xcode - Swift - 表达式类型在没有更多上下文的情况下不明确

macos - 如何在 NSTableView 中放置和控制复选框?

ios - 通过 watchConnectivity 发送一个 NSObject

swift - 如何创建动画GIF

watchkit - 并发症占位符未显示