Swift中的完成处理程序Firebase观察者 [英] Completion handler Firebase observer in Swift

查看:83
本文介绍了Swift中的完成处理程序Firebase观察者的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为一个函数创建一个完成处理程序,它将返回一个对象列表。当它第一次返回值时,它运行良好。但是当firebase数据库发生任何变化并再次观察被调用时,数组大小会增加一倍。为什么它会加倍?

I am making a completion handler for a function which will return a list of objects. When it return value for first time, it works well. But when any change happen into firebase database and again observe gets called, array size gets doubled up. Why it's getting doubled up?

func getStadiums(complition: @escaping ([Stadium]) -> Void){
  var stadiums: [Stadium] = []
  let stadiumRef = Database.database().reference().child("Stadium")
  stadiumRef.observe(.value, with: { (snapshot) in
    for snap in snapshot.children {
      guard let stadiumSnap = snap as? DataSnapshot else {
        print("Something wrong with Firebase DataSnapshot")
          complition(stadiums)
          return
      }
      let stadium = Stadium(snap: stadiumSnap)
      stadiums.append(stadium)
    }
    complition(stadiums)
  })
}

并且这样打电话

getStadiums(){ stadiums
  print(stadiums.count) // count gets doubled up after every observe call
}


推荐答案

您使用的代码声明 stadiums 以外的观察者。这意味着每当对数据库引用的值进行更改时,您都会将数据附加到 stadiums ,而不会清除之前的内容。确保在再次附加快照之前从 stadiums 中删除​​数据:

The code you're using declares stadiums outside of the observer. This means any time a change is made to the value of the database reference, you're appending the data onto stadiums without clearing what was there before. Make sure to remove the data from stadiums before appending the snapshots again:

func getStadiums(complition: @escaping ([Stadium]) -> Void){
  var stadiums: [Stadium] = []
  let stadiumRef = Database.database().reference().child("Stadium")
  stadiumRef.observe(.value, with: { (snapshot) in
    stadiums.removeAll() // start with an empty array
    for snap in snapshot.children {
      guard let stadiumSnap = snap as? DataSnapshot else {
        print("Something wrong with Firebase DataSnapshot")
          complition(stadiums)
          return
      }
      let stadium = Stadium(snap: stadiumSnap)
      stadiums.append(stadium)
    }
    complition(stadiums)
  })
}

这篇关于Swift中的完成处理程序Firebase观察者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆