当我从 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/