ios - FirebaseobserveEventType.childAdded 无法按 promise 工作

标签 ios swift firebase firebase-realtime-database observers

当我从 View Controller 中调用此观察函数时,.childadded 立即返回一个已存储的对象,而不是像 .childadded 那样刚刚添加了 bin .

func observe(callback: RiderVC){
    let ref = DBProvider.Instance.dbRef.child("rideRequests")
    ref.observe(DataEventType.childAdded) { (snapshot: DataSnapshot) in
    if let data = snapshot.value as? NSDictionary {
    let drive = cabRide(ritID: ritID, bestemming: bestemming, 
     vanafLocatie: vanaf, taxiID: taxiID, status: status)
    print(drive)
    callback.alertForARide(title: "Wilt u deze rit krijgen?", message: "Van: \(vanaf), Naar: \(bestemming)", ritID: ritID)
    }
  } 
}

当我使用 .childchanged 尝试此功能时,只有当它像预期的那样发生更改时才会收到警报,但是当执行 .chiladed 时,它只会收到所有来自数据库的请求以及这些请求已经存在。

当我添加新请求时,它也会发出警报。所以它有效,但是我怎样才能摆脱未添加和已经存在的请求呢?

有人知道这个缺陷吗?

最佳答案

这完全按照 promise 进行。来自文档:

Retrieve lists of items or listen for additions to a list of items. This event is triggered once for each existing child and then again every time a new child is added to the specified path. The listener is passed a snapshot containing the new child's data.

一开始这可能看起来很奇怪,但这通常是大多数开发人员想要的,因为它基本上是一种从数据库中特定分支请求所有数据的方式,即使将来会添加新项目。

如果您希望它按照您所描述的方式工作,即在应用程序启动后才在数据库中获取新项目,那么您需要自己做一些工作。首先,您需要为要添加到数据库的对象添加时间戳。然后,您需要进行某种调用,要求通过这些时间戳查询数据库。它可能看起来像这样:

myDatabaseRef.queryOrdered(byChild: "myTimestamp").queryStarting(atValue: <currentTimestamp>)

祝你好运!

关于ios - FirebaseobserveEventType.childAdded 无法按 promise 工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44445119/

相关文章:

iphone - 输入有效值后如何启用 UIButton

ios - Swift 泛型变量

ios - 向没有文本的 UIButton 添加填充

ios - SwiftUI SQLite ForEach 列表数据

firebase - 允许特定用户写访问

ios - 在 fetchedResultsController 委托(delegate)方法中插入行时崩溃 (iOS)

iphone - UICollectionViewController 中加载数据的问题

ios - 如何将 Firebase 中的用户个人列表抓取到表格 View

angular - 嵌套的 Observables : adding an observable as a property of an observable and unwrapping it

iOS 应用程序(挂起)在 iPhone 7 中卡住,但在模拟器中工作