数据库

时间:2018-04-27 16:53:26

标签: swift firebase firebase-realtime-database

我创建了一个从Firebase加载数据的应用。为了节省资源并使应用程序尽可能经济,我实施了查询以为客户端加载合适的数据。那是代码:

    ref.queryOrdered(byChild: "name").queryEqual(toValue: "test").observe(.value, with:{ (snapshot: DataSnapshot) in

        if snapshot.exists(){
            ref.queryOrdered(byChild: "hometown").queryEqual(toValue: "munich").observe(.value, with:{ (snapshot: DataSnapshot) in


                for users in snapshot.children.allObjects as! [DataSnapshot]{
                    if users.key as! String != userId{
                        let item = users.value as? [String: AnyObject]
                        let userid = users.key as! String
                        let Username  = item?["name"] as! String
                        let Userage = item?["age"] as! String
                        let ProfileImage = item?["profileImageUrl"] as! String
                        let firstImage = item?["firstimage"] as! String
                        let seccondImage = item?["seccondimage"] as! String
                        let thirdImage = item?["thirimage"] as! String
                        let fourthImage = item?["fourthimage"] as! String
                        let fifthImage = item?["fifthimage"] as! String
                        let sixtImage = item?["sixtimage"] as! String
                        let sex = item?["sex"] as! String
                        let gender = item?["gender"] as! String
                        let info = item?["info"] as! String
                        let userItem = UserObject(userId: userid, name: Username, age: Userage, sex: sex, gender: gender, profileImage: ProfileImage, fistImage: firstImage, seccondImage: seccondImage, thirdImage: thirdImage, fourthImage: fourthImage, fifthImage: fifthImage, info: info, sixtImage: sixtImage)
                          self.checkValidFences(userItem: userItem, gf: gf)

                    }
                }


            })
        }

    })

遗憾的是,当数据库中的内容发生变化时,该方法始终会加载数据。这就是我在更改数据库中的内容后总是得到冗余值的原因。有没有办法解析一次值

2 个答案:

答案 0 :(得分:2)

您可以通过Reading data once

解决此问题
  

您可以使用observeSingleEventOfType方法来简化此方案:事件回调添加触发器一次,然后不再触发。

  

observeSingleEvent(of:with:)

     

这相当于observeEventType:withBlock :,除了在返回初始数据后立即取消块。

更多信息:

https://firebase.google.com/docs/reference/swift/firebasedatabase/api/reference/Classes/DatabaseReference#observesingleeventofwith

答案 1 :(得分:0)

您可能需要observeSingleEvent而不是observe

所以要替换每一个

.observe(.value

.observeSingleEvent(.value

请参阅Docs