Swift中的完成处理程序Firebase观察者

时间:2017-09-14 22:34:50

标签: ios swift firebase firebase-realtime-database

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

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
}

4 个答案:

答案 0 :(得分:4)

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

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)
  })
}

答案 1 :(得分:0)

此行stadiumRef.observe(.value, with: { (snapshot) in ...实际上添加了一个观察者,每次更改体育场数据时都会调用该观察者。

因为您使用getStadiums(){ stadiums ...调用了两次,所以添加的观察者总数将为2。

这使得在第二次调用中线stadiums.append(stadium)被调用两次。

我的建议是使用stadiumRef.observe()一次,而不是从getStadiums()调用它。

答案 2 :(得分:0)

创建如下模型

class OrderListModel: NSObject {
    var Order:String?
    var Date:String?
}

在视图控制器中使用以下代码,您应该能够在表视图中看到内容

func getOrdersData()  {
    self.orderListArr.removeAll()
    let ref = Database.database().reference().child(“users”).child(user).child("Orders")

        ref.observe(.childAdded, with: { (snapshot) in
            print(snapshot)
            guard let dictionary = snapshot.value as? [String : AnyObject] else {
                return
            }

            let orderObj = OrderModel()
            orderObj.Order = dictionary[“Order”] as? String
            orderObj.Date = dictionary[“Date”] as? String

            self.orderListArr.append(orderObj)
            self.tableView.delegate = self
            self.tableView.dataSource = self
            self.tableView.reloadData()

        }, withCancel: nil)
}

答案 3 :(得分:0)

func ListenForChildrenAdded() {

let registerToListenTo = "YourPathHere"

ref.child(registerToListenTo).observeSingleEvent(of: .value) { (snapshot) in
    
    let initialChildren = snapshot.childrenCount
    var incrementer = 0
    
    ref.child(registerToListenTo).observe(.childAdded, with: { (snapshot) in
        
        incrementer += 1
        print("snapshot: \(snapshot.key) #\(incrementer)")

        if incrementer == initialChildren {
            print("-> All children found")
        } else if incrementer > initialChildren {
            print("-> Child Was Added - Run Some Code Here")
        }
        
    })
}}