【问题标题】:How can I get results for both existing and new children in Firebase?如何在 Firebase 中获取现有子级和新子级的结果?
【发布时间】:2016-04-18 00:07:45
【问题描述】:

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

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

【问题讨论】:

    标签: ios swift firebase firebase-realtime-database


    【解决方案1】:

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

    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 是使用所有匹配的子级调用的,因此您必须循环遍历块中的子级:

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

    【讨论】:

    • 答案的第二部分应该是 query.observeEventType(.Value 吗?
    • 好收获。固定!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多