I am creating a workout app in Apple Watch with the HKWorkoutSession and using HKLiveWorkoutBuilder to access the live data like distance, calories, heart rate. The user can pause and resume the workout as well. Suppose I pause the workout after 5 minutes and then kill or force quit the app. After it when I relaunch the app again after 5 minutes more then the builder elapsed time does not includes the pause duration because the activity is again started from the start time. How can I get the current working workout session that I last created before killing the application? This works well when the application is either in foreground or in background.
How can I get the current active workout session when the app is relaunched after killing the app in Apple Watch?
You would need to implement workout recovery. Basically in your WKExtensionDelegate you need to implement handleActiveWorkoutRecovery(). In this scenario do not start a new HKWorkoutSession, but call into recoverActiveWorkoutSession(completion:) to recover the original session. The HKLiveWorkoutBuilder associated with the recovered session should have the correct start date and include all pause/resume events. You would still need to attach a new HKLiveWorkoutDataSource to the builder.
Documentation for this is here:
https://developer.apple.com/documentation/healthkit/hkhealthstore/2962889-recoveractiveworkoutsession
There is also a good explanation for this on the WWDC 2008 session:
https://developer.apple.com/videos/play/wwdc2018/707/
Documentation for this is here:
https://developer.apple.com/documentation/healthkit/hkhealthstore/2962889-recoveractiveworkoutsession
There is also a good explanation for this on the WWDC 2008 session:
https://developer.apple.com/videos/play/wwdc2018/707/
Thanks, I will try with the recoverActiveWorkoutSession(completion:) to recover the original session but as per the apple documentation, it has written there that use this in case the app was crashed during workout. So, will it work in the same way if my app was not crashed but was killed by user himself?