简体   繁体   中英

How to reflect childChanges on tableView - IOS Swift Firebase

I have a tableview and would like to add childChange function to my tableview, but I have tried to do so, and instead updating the Child, my Tableview adds another row with the changed child, so I have one old valued row and new updated row listed in my tableview.

in my viewdidload I have defined my firebase reference and added two functions:

        ref = Database.database().reference().child("paris")
    fetchBars()
    refreshBars()

and have defined below viewdidload two functions:

    func fetchBars(){

    ref.observe(.childAdded, with: { (snapshot) in
        guard let bar = Bar.bar(from: snapshot) else {return}

        self.bars.append(bar)
        self.tableView.reloadData()
    })

}
func refreshBars(){
    ref.observe(.childChanged, with: { (snapshot) in
        guard let bar = Bar.bar(from: snapshot) else {return}
        self.bars.append(bar)
        self.tableView.reloadData()
    })
}

For me it would be helpful if I could make an observer of ChildAdded and ChildChange in the single function. Please help me and thank you in advance.

CellforRow:

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "RestoCell", for: indexPath) as! ViewControllerCell

    let bar = bars[indexPath.row]
    cell.RestName.text = bar.barName
    cell.RestAddress.text = bar.barAddress
    cell.RestImage.sd_setImage(with: URL(string: bar.barMainImage))
    cell.percentLabel.text = bar.percentage


    return cell
}

You need to update the row instead of adding a new one, first of all, you need to add a unique id for the Bar class to use it to get the index of the row, it will be something like this:

func refreshBars(){
    ref.observe(.childChanged, with: { (snapshot) in
        guard let bar = Bar.bar(from: snapshot) else {return}
        // you need to find the index of the bar
        let index = self.bars.index(where: { otherbar in bar.id == bar.id })!
        // remove the old one
        self.bars.remove(at: index)
        // add the new one
        self.bars.insert(bar, at: index)
        // reload the row with fade animation
        self.tableView.reloadRows(at: [IndexPath(row: index, section: 0)], with: .fade)
    })
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM