I'm developing a workout app with a mirrored workout session. I'm having problems with sessions being out of sync. For example, when the workout is ended, it takes somewhere around a minute or two for it to actually fully end, so if during this time I start a new workout, then the sessions will be out of sync. I am using healthStore.recoverActiveWorkoutSession()
to recover the workout session but it doesn't always work very well and in particular in the case when a workout has been manually ended (but ending hasn't completed) it enters an out of sync mode.
The reason why this case is happening is because I have an third party sensor connected to this mirrored workout session and if the sensor is out of range or turned off, I end the workout. However, if the person had accidentally gone out of range, they would reconnect to the app and restart the workout as soon as they realize and in that case, when the workout hasn't fully ended, it doesn't recover appropriately.
Following the suggestions from the post below, I do my post-workout cleanup when the delegate records the state change. But this does not help with the case where a new workout is started before the previous one ends. Is there a way to speed up the end process? Why is my HKWorkoutSession (usually) not ending?
recoveractiveworkout
doesn't work.
One thing that sometimes works is to have a new workout automatically start once the ended session is detected. However, this creates other unexpected bugs and unintentional consequences.
Also, this is my startworkout function with recovery:
func startWorkout(workoutConfiguration: HKWorkoutConfiguration) async throws {
WKInterfaceDevice.current().play(.success)
if let recoveredSession = try await healthStore.recoverActiveWorkoutSession() {
print("Recovering existing session...")
session = recoveredSession
session?.delegate = self
try await session?.startMirroringToCompanionDevice()
return
} else {
// Create new session if recovery failed or wasn't needed
session = try HKWorkoutSession(healthStore: healthStore, configuration: workoutConfiguration)
session?.delegate = self
try await session?.startMirroringToCompanionDevice()
session?.startActivity(with: Date())
DispatchQueue.main.asyncAfter(deadline: .now() + 10, execute: {
self.session?.pause()
print(self.session?.description ?? "No session")
})
}
}