Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Observing changes in HealthKit data using HKObserverQuery

Tags:

ios8

When I setup an HKObserverQuery, the update handler always gets immediately called (something I didn't expect). It also gets called when I add data points through Health.app, as you would expect. I am tending to think I am not doing something right with the completion handler, but the docs are fairly sparse on what is supposed to happen here.

Question: Below is basically what I'm doing. Is this expected behavior, or am I missing something?

    func listenForUpdates() {
        let bodyMassType = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMass)
        let updateHandler: (HKObserverQuery!, HKObserverQueryCompletionHandler!, NSError!) -> Void = { query, completion, error in
            if !error {
                println("got an update")
                // ... perform a sample query to get the actual data
                completion() // is this the right thing to do?
            } else {
                println("observer query returned error: \(error)")
            }            
        }
        let query = HKObserverQuery(sampleType: bodyMassType, predicate: nil, updateHandler: updateHandler)
        healthStore?.executeQuery(query)
    }

Edit: discovered completion handler should only be called when there wasn't an error, so moved into the !error block. An error is present when the app is not authorized.

like image 431
jaydfwtx Avatar asked Feb 12 '23 18:02

jaydfwtx


1 Answers

Yes, this is expected behavior. The update handler will always be called on first execution so that you can use it to fetch your initial data (from your sample query, anchored object query, etc) and populate your UI.

The completion handler is only necessary if you intend to use background delivery, it informs HealthKit that you have received and processed the data you need so that HealthKit knows to stop launching your app in the background. If you have not registered your app for background delivery, then the completion handler is essentially a no-op and you don't need to worry about it.

like image 110
jrushing Avatar answered Feb 15 '23 06:02

jrushing