Completion handler Firebase observer in Swift

后端 未结 4 1483
日久生厌
日久生厌 2021-01-17 01:11

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 fire

4条回答
  •  别那么骄傲
    2021-01-17 01:33

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

提交回复
热议问题