ios - Firebase .observeSingleEvent(:with:) method is retrieving cached/old data

标签 ios swift firebase firebase-realtime-database

<分区>

[免责声明] 在我自己努力解决这个问题之后,我亲自发布并回答了这个问题,相关地,我注意到很多人仍然这样做

上下文

我正在开发一个 iOS 移动应用程序,并且 - 对于这个特定项目 - 决定使用 Firebase 实时数据库 作为我的后端基础设施。


问题

当使用 .observeSingleEvent(of:with:) 方法在特定节点查询数据时,我总是发现自己检索的是缓存数据或旧数据,而不是新更新的数据。

在某些情况下,连续两次调用该方法可以检索所需的服务器数据


尝试

  1. 根据 Firebase documentation 在相关节点使用 .keepSynced(true)

    automatically downloads the data at these locations and keeps it in sync even if the reference has no active listeners

最佳答案

概览

通过文档,您注意到有两种主要方法可以将 Firebase 实时数据库 中的数据查询到您的 iOS 移动应用程序中

  1. .observe(_:with:) 方法,根据Firebase Documentation ,持续监听特定节点的变化,并在每次数据在后者发生变化时触发回调。

    This method is triggered once when the listener is attached and again every time the data, including any children, changes. The event callback is passed a snapshot containing all data at that location, including child data. If there is no data, the snapshot will return false when you call exists() and nil when you read its value property.

  2. .observeSingleEvent(of:with:) 方法,根据Firebase Documentation , 恰好被调用一次。

    In some cases you may want a callback to be called once and then immediately removed, such as when initializing a UI element that you don't expect to change. You can use the observeSingleEventOfType method to simplify this scenario, [in which] the event callback [is triggered] once and then does not trigger again.


问题

在了解了查询数据的不同可能方法之后,您已经意识到 .observeSingleEvent(of:with:) 方法更适合您当前的数据库读取需求。但是,无论您修改数据库多少次,在您的应用程序中实现它都会继续检索缓存数据和旧数据。您在相关数据库引用中调用了 .keepSynced(true),但没有成功。您选择了 .observe(_:with:) 方法,一切都开始正常运行。

那么可能是什么问题?


解决方案

如果您的数据库安全规则无效,您可能遇到此问题的原因是完全合乎逻辑的。这些可以很容易地阻止您检索所需的数据和同步您的实时数据库。

假设您正在尝试同步 myRef 数据库引用。您需要设置正确的规则,允许从此数据库引用中读取数据 - 类似于 ".read"= true"

[警告] 请注意这些数据库安全规则。不正确的规则可能会导致严重的不良行为,例如人们非法读取和/或写入您的数据库。关于如何设置完美安全规则的好视频是 The key to firebase security - Google I/O 2016

关于ios - Firebase .observeSingleEvent(:with:) method is retrieving cached/old data,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52478008/

相关文章:

ios - 如何退出 SWRevealViewController?

ios - MapView 相机在 iOS Swift 中没有改变

swift - 类型 'T' 不符合协议(protocol) 'EntityType'

ios - CLGeocoder().reverseGeocodeLocation;处理程序应该是什么?

javascript - firebase - 使用 key 获取子数据库引用

firebase - 获取 Firebase 中的节点创建时间

ios - iOS 11修复了滚动输入错误+抖动

javascript - 滚动到维基百科上的特定段落

ios - 如何在应用程序后台循环调用 Rest Web 服务?

javascript - 在 Firebase Auth 之后将用户数据添加到 firestore