ios - Firebase 按值观察从缓存数据中获取旧值

标签 ios swift firebase swift3 firebase-realtime-database

启用 firebase 持久性后,我一直面临一些问题,我有机会阅读其余已发布的问题并查看那里的答案,但仍然没有按预期工作。

我启用了 firebase 持久性并使用按值观察来获取特定节点的最新更新。它不仅不断获取旧值,而且一旦我离开一个特定的 View Controller 并返回到该 View Controller ,该值就会更改为最近的值。

是否有一种正确的方法可以在第一次调用时请求最近的值?

我试过的代码:

 // MARK: Bill authenticate function

func authenticateBill(completion: @escaping (_ bill: Double?, _ billStatus: BillError?) -> Void) {

    // Observe incase bill details exist for current case
    let billRef = self.ref.child("bills").child((caseRef?.getCaseId())!)

    billRef.observe(FIRDataEventType.value, with: { (billSnapshot) in

        if !billSnapshot.exists() {
            completion(nil, BillError.unavailable)
            return
        }

        if let billDictionary = billSnapshot.value as? [String: AnyObject] {
            let cost =  billDictionary["cost"] as! Double

            print("Cost: ", cost)

            completion(cost, nil)
        }

    })

}

最佳答案

不,启用持久化后,您的第一个回调将包含来自缓存的立即可用值(如果有),然后是来自服务器的更新(如果有)。您无法向 SDK 指示您想要缓存数据还是新数据。

如果您希望在启用持久性的情况下始终使特定位置保持最新状态,您可以使用 keepSynced 向 SDK 指示它应该始终在该位置监听和缓存数据。这会带来不确定的带宽成本,具体取决于数据更改的频率。

您可以使用 REST API 请求新数据,而无需通过任何缓存机制。

关于ios - Firebase 按值观察从缓存数据中获取旧值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45538911/

相关文章:

ios - 如何轻轻地从 map View 中删除注释?

ios - 从核心数据删除后重新加载表格 View

swift - 快速编译器的奇怪行为

javascript - Firebase 与 JavaScript

Angular js : How to authenticate before route changes

ios - 如何获取按钮相对于 super View 的坐标?

iOS 蓝牙中央管理器

ios - 通知控制中心同时播放多个音频

ios - 使用 swift NSObjects 和 JSON 的 EXC_BAD_INSTRUCTION

firebase - Firebase_auth 中未定义的类 'UserUpdateInfo'(Flutter 2020)