How to query for HealthKit (HKWorkout) updates when app is in background?
Asked Answered
D

1

6

EDIT to add my updated code which I based on WWDC 2016's Getting the Most Out of Healthkit talk, but I still am not getting my print statement with the new workout to fire unless I open the app?

I'm trying to observe for new workouts on the iPhone after they've been saved on the Apple Watch. Below is the code I'm running in didFinishLaunching. To test it, I'm running Xcode on my iPhone App...building and running, then navigating back to the home screen. Then starting and saving a workout on my watch, however my print statements aren't printing in the console. What am I missing?

func startObservingNewWorkouts() {

    let sampleType =  HKObjectType.workoutType()

    //1. Enable background delivery for workouts
    self.healthStore.enableBackgroundDelivery(for: sampleType, frequency: .immediate) { (success, error) in
        if let unwrappedError = error {
            print("could not enable background delivery: \(unwrappedError)")
        }
        if success {
            print("background delivery enabled")
        }
    }

    //2.  open observer query
    let query = HKObserverQuery(sampleType: sampleType, predicate: nil) { (query, completionHandler, error) in

        self.updateWorkouts() {
            completionHandler()
        }


    }
    healthStore.execute(query)

}

func updateWorkouts(completionHandler: @escaping () -> Void) {

    var anchor: HKQueryAnchor?

    let sampleType =  HKObjectType.workoutType()

    let anchoredQuery = HKAnchoredObjectQuery(type: sampleType, predicate: nil, anchor: anchor, limit: HKObjectQueryNoLimit) { [unowned self] query, newSamples, deletedSamples, newAnchor, error in

        self.handleNewWorkouts(new: newSamples!, deleted: deletedSamples!)

        anchor = newAnchor

        completionHandler()
    }
    healthStore.execute(anchoredQuery)


}

func handleNewWorkouts(new: [HKSample], deleted: [HKDeletedObject]) {
    print("new sample added = \(new.last.startTime!)")
}
Dearing answered 2/4, 2018 at 16:5 Comment(1)
Are you calling startObservingNewWorkouts every time you open the app? If not, I would be interested to find out what is your solution to handle this. I want to build observe the new running type workouts from HealthKit and fetch them to my app, but I want to do it using HKSampleQuery, not through HKObserverQuery. And I want to use the background observer only to do some action with the new running workouts. I am interesting how to combine the backgroudn observation and the workout fetching mechanism in the best way possible. – Womankind
D
3

Turns out this code πŸ‘† works, its just that I was testing in the simulator and apparently the Observer Query does NOT fire when running in the simulator but it DOES fire when running on device

Dearing answered 4/4, 2018 at 20:15 Comment(9)
Will this work even when the device is locked? I want to send updates in health kit data to my server whenever there is a change even when the app is on background or device is locked. Is that possible? – Khaki
Yep, it will process even when the device is locked. – Dearing
But this will work only when i add Background modes in the capabilities right? That will fetch data only for 180 secs. Correct me if i am wrong. Then how can i constantly monitor the health data when app is in background? – Khaki
Just test it with print statements, Xcode will still run your print statements when the phone is locked. πŸ‘ – Dearing
Can you please help me with the full source code on how you achieved this? there is only a piece of code available in your question. I want to get constant updates from watch app and sync it to health kit of iPhone and if there is any change in health kit info, my app which is in background with the device locked should send the updates to server ? – Khaki
I started a HealthKit developer Slack Channel: join.slack.com/t/healthkitdevelopers/shared_invite/… post your Q in here and we'd be happy to help you – Dearing
@Dearing is that slack group still around? I'd love an updated invite link. --mark – Patrilocal
@MarkPerkins sure thing, here's the link! join.slack.com/t/healthkitdevelopers/shared_invite/… – Dearing
Thank you @Dearing – Patrilocal

© 2022 - 2024 β€” McMap. All rights reserved.