How to discard a running HKWorkoutSession

44 views Asked by At

I'm building a companion watch app for my workout tracker app and, I would like to discard a workout session triggered on the watch when user closes a workout session on the iOS app. But it seems like there is no discard or cancel method on HKWorkoutSession. How can I achieve this?

1

There are 1 answers

0
emrepun On

Although there is no discard or cancel method for HKWorkoutSession, we can use its associated workout builder (HKLiveWorkoutBuilder) to discard workout before calling end on the session. So, we can cancel a running HKWorkoutSession as follows (Add this method to your watchOS workout manager where you keep a reference to the running session):

func discardCurrentWorkoutSession() {
    guard let session else {
        return
    }
    let builder = session.associatedWorkoutBuilder()
    builder.discardWorkout()
    session.end()
    self.session = nil
}

Then the session will be discarded and no data will be saved to HealthKit.

Related Questions in HKWORKOUTSESSION