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

大兔子大兔子 提交于 2019-12-08 06:32:24

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, withCompletion completion: (() -> Void)? = nil) {
    let stepsReference = databaseInstance.reference(withPath: stepsPath)
    stepsReference.setValue(steps) { (error, _) in
        if let completion = completion {
            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 Firebase operation completes correctly now.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!