HKObserverQuery background delivery stops working after calling completionHandler

995 Views Asked by At

So according to Apple, I need to call the HKObserverQueryCompletionHandler after the updateHandler is triggered from data being added to HK.

But as soon as I call the completionHandler, the observer query stops giving any more updates in the background..

Here is my code:

guard let sampleType = sample as? HKQuantityType else { return nil }

let query = HKObserverQuery(sampleType: sampleType, predicate: nil, updateHandler: { query, completionHandler, error in

    completionHandler()

    IamExecutingHKStatisticsCollectionQueryHere()
})

healthStore?.execute(query)
healthStore?.enableBackgroundDelivery(for: sampleType, frequency: .hourly, withCompletion: { success, error in

})

If I don't call the completionHandler, everything works fine but I have never tested for long periods of time..

2

There are 2 best solutions below

3
On

Calling completionHandler() indicates that you are done processing new data. Only call it once you have processed the results of the queries you execute in response to updateHandler being called. If you call completionHandler() early as you are now, the system will stop running your app in the background before you have a chance to process data.

0
On

You must call the completionHandler otherwise the updateHandler will not be called.

ref: https://developer.apple.com/documentation/healthkit/hkobserverquerycompletionhandler

"You must call this block as soon as you are done processing the incoming data. Calling this block tells HealthKit that you have successfully received the background data. If you do not call this block, HealthKit continues to attempt to launch your app using a back off algorithm. If your app fails to respond three times, HealthKit assumes that your app cannot receive data, and stops sending you background updates."