0

I can detect workout started on backgroun with apple watch, with below code

let workoutevent =  HKObjectType.workoutType()

 if store.authorizationStatus(for: workoutevent) != HKAuthorizationStatus.notDetermined {
            store.enableBackgroundDelivery(for: workoutevent, frequency: .immediate, withCompletion: { (worked, error) in
                print(worked)
                print(error)
                print("workoutevent enableBackgroundDelivery")
                guard worked else {
                    self.logger.error("Unable to set up background delivery from HealthKit: \(error!.localizedDescription)")
                    print("workoutevent unable to set up background ")
                    fatalError()
                }
                if error != nil {
                    print("workoutevent error is ")
                    print(error)
                }
            })


            backgroundObserver3 =
            HKObserverQuery(sampleType: workoutevent,
                            predicate: nil,
                            updateHandler: processUpdate3(query:completionHandler3:error:))
            if let queryworkout = backgroundObserver3 {
                print("Starting  workoutevent333 the background observer query.\(queryworkout)")
                store.execute(queryworkout)
            }

        }else{
            print("not determined....")
        }

whenever I started workout on apple watch, it goes to processUpdate3 very well, but what I need to know is to when user finish workout. how can I detect it ?

func processUpdate3(query: HKObserverQuery,
                       completionHandler3: @escaping () -> Void,
                       error: Error?) {
        print("come here when work out started ")

........... }

Pd.Jung
  • 113
  • 1
  • 3
  • 13

1 Answers1

1

I don't see it in your code. But somewhere you must have an HKWorkoutSession. My app is set up to track running and I configure the session to begin like so;

    let configuration = HKWorkoutConfiguration()
    configuration.activityType = .running

    do {
        // HKWorkoutSession is set up here.
        session = try HKWorkoutSession(healthStore: healthStore, configuration: configuration)
        workoutBuilder = session.associatedWorkoutBuilder()
    } catch {
        // handle errors
    }

When the users taps the end workout button I call session.end()

Here is a link to the documentation.

Dan O'Leary
  • 916
  • 9
  • 20