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
iOS Charts - Single Values Not Showing Swift
Sandbox Entitlement to Script Itunes via Nsapplescript
Skphysicscontact Not Detecting Categorybitmask Collision
Cache That Can Purge Unused Objects by Demand
Uislider Handle Changes Width on Different Size Ipads
Swift Execute Command Line Command in Sandbox Mode
Create Tab Bar Controller and Navigation Controller
Why I Can't Access My 3Rd Level Coredata Data in Swift
Weird Behaviour in Swiftui+Combine When Class -> Struct
Write Data to Firebase in The Background After Retrieving Steps with Healthkit's Background Delivery
Getting an Ip Address and Port Number from a Sockaddr_In Struct in Swift
Need Clarification on Anyobject in Swift
Uicollectionview + Nsfetchedresultscontroller in Swift 3
How to Set .Realm File on Realm
Can't Unwrap Optional.None When Setting Window Background Color