如何在 Firebase 中获得现有和新 children 的结果?

How can I get results for both existing and new children in Firebase?

我正在尝试在 Firebase 中为我的 swift iOS 应用创建查询。我在查询中遇到的问题是它不会立即从 firebase 获取坐标,除非它们被更改。我尝试了所有其他观察者类型,但 none 似乎有效。我知道我目前要更改观察者类型,但我需要正确的方法让它在应用程序加载后立即获取位置并使用 firebase 进行更新。 .childAdded 立即获取位置,但在 Firebase 上更改时不会更新。

userDirectory.queryOrderedByChild("receiveJobRequest")
             .queryEqualToValue(1)
             .observeEventType(.ChildChanged  , withBlock: {snapshot in
        var cIhelperslatitude = snapshot.value["currentLatitude"]
        var cIhelperslongitude = snapshot.value["currentLongitude"]

如果你想监听多种事件类型,你需要注册多个监听器。

let query = userDirectory.queryOrderedByChild("receiveJobRequest")
                         .queryEqualToValue(1)

query.observeEventType(.ChildAdded, withBlock: {snapshot in
    var cIhelperslatitude = snapshot.value["currentLatitude"]
    var cIhelperslongitude = snapshot.value["currentLongitude"]

query.observeEventType(.ChildChanged, withBlock: {snapshot in
    var cIhelperslatitude = snapshot.value["currentLatitude"]
    var cIhelperslongitude = snapshot.value["currentLongitude"]

您可能希望将该公共代码重构为一个方法,您可以从 .ChildAdded.ChildChanged 块中调用该方法。

或者,您可以注册一个 .Value 事件,每次查询下的值更改时,初始值 都会触发该事件。但是由于 .Value 是用所有匹配的 children 调用的,所以你必须在你的块中循环 children:

query.observeEventType(.Value, withBlock: {allsnapshot in
    for snapshot in allsnapshot.children {
        var cIhelperslatitude = snapshot.value["currentLatitude"]
        var cIhelperslongitude = snapshot.value["currentLongitude"]
    }