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..
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 toupdateHandler
being called. If you callcompletionHandler()
early as you are now, the system will stop running your app in the background before you have a chance to process data.