5

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!)")
}
GarySabo
  • 5,806
  • 5
  • 49
  • 124

1 Answers1

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

GarySabo
  • 5,806
  • 5
  • 49
  • 124
  • 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? – Vidhya Sri Jul 06 '18 at 06:33
  • Yep, it will process even when the device is locked. – GarySabo Jul 06 '18 at 12:57
  • 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? – Vidhya Sri Jul 10 '18 at 08:06
  • Just test it with print statements, Xcode will still run your print statements when the phone is locked. – GarySabo Jul 10 '18 at 12:41
  • 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 ? – Vidhya Sri Jul 10 '18 at 17:14
  • I started a HealthKit developer Slack Channel: https://join.slack.com/t/healthkitdevelopers/shared_invite/enQtMzEyOTg1NTk2MDY2LTA4YTUxMDQzOWIxYjEwMjhhZDJhY2EzMjJkMzg3OThhY2MzOWNkNDNlNjY5YWFhNDAyNmFiMGQ2YmM0NzQxYTA post your Q in here and we'd be happy to help you – GarySabo Jul 10 '18 at 23:12
  • 1
    @GarySabo is that slack group still around? I'd love an updated invite link. --mark – Mark Perkins Mar 25 '21 at 00:14
  • @MarkPerkins sure thing, here's the link! https://join.slack.com/t/healthkitdevelopers/shared_invite/zt-3zs7jjj6-vieepfOhfnlxSMosiP3Yfw – GarySabo Mar 25 '21 at 22:07
  • Thank you @GarySabo – Mark Perkins Mar 26 '21 at 23:27