【问题标题】:Swift & Firebase - Out of sync after isPersistenceEnabledSwift & Firebase - isPersistenceEnabled 后不同步
【发布时间】:2018-06-18 07:49:53
【问题描述】:

我的应用程序和 firebase 数据库之间的连接出现问题。添加后:

Database.database().isPersistenceEnabled = true

对于我的 AppDelegate,一些数据不同步。 要获取我的数据,我使用:

self.ref?.child("Stores").observe(.childAdded, with: { (snapshot) in
        if let dictionary = snapshot.value as? [String: AnyObject] {
            let store = Store()
            store.Latitude = dictionary["Latitude"]?.doubleValue
            store.Longitude = dictionary["Longitude"]?.doubleValue
            store.Store = dictionary["Store"] as? String
            store.Status = dictionary["Status"] as? String
            stores.append(store)

            DispatchQueue.main.async {
                self.performSegue(withIdentifier: "LogInToMain", sender: nil)
            }
        }
    })

在下一个 ViewController 上,我使用日期在地图上进行注释。像这样:

func createAnnotation(Latitude:Double, Longitude:Double, Store:String, Status:String) {
    let annotation = CustomPointAnnotation()
    let latitude: CLLocationDegrees = Latitude
    let longitude: CLLocationDegrees = Longitude
    annotation.coordinate = CLLocationCoordinate2DMake(latitude, longitude)
    annotation.title = Store
    annotation.imageName = "\(Status).png"
    map.addAnnotation(annotation)
}

但问题是,注释的数据不再随数据库而改变。该应用程序需要先打开,然后关闭,然后再次打开,然后才能正确显示数据。谁能帮忙解决这个问题?

【问题讨论】:

  • 我目前正在自己​​解决 Firebase 的问题。我想你可能会发现你的观察块在启用持久性的情况下被多次调用。第一次从本地存储返回值,第二次从服务器返回。
  • firebase.google.com/docs/database/admin/retrieve-data 对于每个现有的孩子触发一次此事件,然后每次将新的孩子添加到指定路径时再次触发。我会在下一个 VC 中使用 .childChanged 或 .value。顺便说一句@PeterHaddad 提到了observeSingleEventOfType,但根据我的经验,在大多数情况下,这绝对不会让你得到最新的结果。

标签: ios swift firebase firebase-realtime-database data-persistence


【解决方案1】:

由于您正在使用:

Database.database().isPersistenceEnabled = true

那么您需要使用keepSynced(true),以便数据保持同步。

持久性行为:

通过启用持久性,Firebase 实时数据库客户端在联机时将同步的任何数据都会持久保存到磁盘并且可以脱机使用,即使用户或操作系统重新启动应用程序也是如此。这意味着您的应用程序可以使用存储在缓存中的本地数据像在线一样工作。侦听器回调将继续触发本地更新。

keepSynced(true):

Firebase 实时数据库为活动的侦听器同步并存储数据的本地副本。此外,您可以使特定位置保持同步。

更多信息请查看:https://firebase.google.com/docs/database/ios/offline-capabilities

【讨论】:

  • 谢谢!我已经添加:(在初始 ViewController 上的 viewDidLoad()) let storesRef = Database.database().reference(withPath: "Stores") storesRef.keepSynced(true) 但问题仍然存在:'(
  • 你找到解决办法了吗?
  • 我们应该从哪里调用 Database.database().isPersistenceEnabled = true .....in func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) ->布尔 {} 或 ?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多