HealthKit - “Stopped workout session cannot be restarted”

I am using the following code to record the heart rate from the internal watch sensor, which works fine! But when I stop the workout and want to start a new I am getting the error: workoutSession didFailWithError = Error Domain=com.apple.healthkit Code=3 "Stopped workout session cannot be restarted" UserInfo={NSLocalizedDescription=Stopped workout session cannot be restarted}

I think I have to clear in any kind the HKWorkoutSession *workoutSession and init it new but I don't know how?


Here is the code I am using:


@interface InterfaceController()

{

ExtensionDelegate *extensionDelegate;


/

HKHealthStore *healthStore;

HKWorkoutSession *workoutSession;

HKUnit *heartRateUnit;

HKQueryAnchor *anchor;

}


healthStore = [[HKHealthStore alloc] init];

workoutSession =[[ HKWorkoutSession alloc] initWithActivityType:HKWorkoutActivityTypeCrossTraining locationType:HKWorkoutSessionLocationTypeIndoor];

heartRateUnit = [HKUnit unitFromString:@"count/min"];

anchor = [HKQueryAnchor anchorFromValue:HKAnchoredObjectQueryNoAnchor];

workoutSession.delegate = self;


[healthStore startWorkoutSession:workoutSession];


How can I clear the workout session after stopping it for starting a new workout session:

[healthStore endWorkoutSession:workoutSession];


Not working:


workoutSession = nil;

Replies

I have had this issue for months as well and I just figured out how to solve this issue! For me, starting and stopping my first workout worked fine. When I started the second workout I noticed that the workout icon on the watch face did not appear, thought the heart rate sensor was active when I was in the app. Stopping the second workout produced the same error you were seeing. But, if I started and stopped a third workout it behaved the same as the first! I figured something was keeping a reference incorrectly somewhere, and the only place I was assigining it to other than the delegate was the HKHealthStore. So, before I start a workout, if I re-init my HKHealthStoreeverything works as expected.

lehn0058,


thank you SO much for your comment! Solved the issue (same as yours) that I was having. Literally couldn't find help on this anywhere else. Apple should include this info in its documentation haha. Cheers!