swiftuiwidgetapple-watchwatchoshealthkit

responding to WatchOS 10 workout widget play/pause button in third party app


I've been searching Apple's documentation (and the rest of the web) for this and I haven't found a mention. Also looked through HKWorkoutSession.h for anything in WatchOS 10 that might be related. I have a workout app for Apple Watch. It appears that using HKWorkoutSession automatically activates Apple's own stack widget in WatchOS 10, showing elapsed workout time and giving the user a play/pause button. However, it doesn't appear to give you automatic access to the play/pause button event. I've set breakpoints in the .onOpenURL(perform: { url in method I have implemented for my own widget. I also set a breakpoint in

func workoutSession(_ workoutSession: HKWorkoutSession,
                        didChangeTo toState: HKWorkoutSessionState,
                        from fromState: HKWorkoutSessionState,
                        date: Date)

Apple's widget button doesn't trigger either of these methods.

Question: How do I listen for the play/pause button? Alternatively, can I turn this widget off for my app, given that I'm implementing my own stack widget?

Note: My own widget using the .onOpenURL works as desired, as does my usage of the HKWorkoutSessionDelegate.


Solution

  • You might try this solution, I did and it solves the problem:

        func workoutSession(_ workoutSession: HKWorkoutSession, didGenerate event: HKWorkoutEvent) {
            if(event.type == HKWorkoutEventType.pauseOrResumeRequest) {
                if self.running { // HKWorkoutSessionState is 'running'
                    pauseWorkout()
                }
                else {
                    resumeWorkout()
                }
            }
        }
    

    Hope it helps!