Write Data to Firebase in The Background After Retrieving Steps with Healthkit's Background Delivery

Write data to Firebase in the background after retrieving steps with HealthKit's background delivery

Ok, I solved this. The problem was that I was calling the completionHandler, telling HealthKit that I was done with my operation, before the saving to Firebase was actually completed. Saving to Firebase is done asynchronously.

I added a completion handler to StepsManager.shared.updateUserSteps function:

func updateUserSteps(_ steps: Double, completion: (() -> Void)? = nil) {
let stepsReference = databaseInstance.reference(withPath: stepsPath)
stepsReference.setValue(steps) { _, _ in
completion?()
}
}

which is triggered when the databaseRef.setValue has completed. I then updated the observer query to the following:

self?.getTodaysStepCount(completion: { steps in
StepsManager.shared.updateUserSteps(steps) {
completionHandler() // the HKObserverQueryCompletionHandler
}
})

The Firebase operation completes correctly now.

health kit observer query always called when the app becomes active

Why do you want to prevent the updateHandler from firing?

You can't control when the updateHandler of an HKObserverQuery fires while the query is running. You can prevent it from being called at all by stopping the query. It is designed to be called whenever there might be new HealthKit data matching your predicate. You should design your updateHandler such that it doesn't matter when it is called.

If you really wanted the observer query to not fire when your app returns to the foreground, you would need to stop the query completely with -[HKHealthStore stopQuery:] when your app enters the background, before it suspends.



Related Topics



Leave a reply



Submit