Search code examples
swiftuitableviewfirebasefirebase-realtime-databasefirebaseui

Remove a Child in Firebase Database using FirebaseUI


FirebaseUI keeps track of changes in the DB and synchronises it with my TableView, which is good. I need the user to be able to remove childs by himself when swiping a tableView cell.

I'm using populateCellWithBlock to fill my table. However, I couldn't find anything about how to delete a child. What I have:

override func viewDidLoad() {
    super.viewDidLoad()

    dataSource = FirebaseTableViewDataSource.init(query: getQuery(),prototypeReuseIdentifier: "Cellident", view: self.tableView)

    dataSource?.populateCellWithBlock { (cell: UITableViewCell, obj: NSObject) -> Void in
        //Filling the table:

        let customCell = cell as! CustomCellTableViewCell

        let snap = obj as! FIRDataSnapshot
        let childString = snap.value as! [String : AnyObject]
        let data = childString["data"] as? String

        customCell.urlLabel.text = String(data!)

    }
    tableView.dataSource = dataSource
    tableView.delegate = self
}

Now, I've tried several approaches with Arrays, but couldn't figure out how to keep them synced. My problem is I can't figure out how to delete a child at a specific path, meaning the child which is in a single cell. How do I make sure the cell which is swiped-to-delete triggers the removal of the child from that cell?

My question is what the best practice here is, if I want the user to be able to remove a child. Obviously it needs to be removed from the database and from the tableView, but since FirebaseUI keeps track of changes, I'm sure there must be a way using FirebaseUI to delete it?


Solution

  • So after trying around, I found a solution. I'm using MGSwipeTableCell in order to make the cells swipeable and show a delete button, then inside it's convenience callback, I simply did:

    let removebtn = MGSwipeButton(title: "Delete", backgroundColor: UIColor.redColor(), callback: {
                (sender: MGSwipeTableCell!) -> Bool in
    
                snap.ref.removeValue() //This
    
                return true
            })
    

    Where snap is:

    let snap = obj as! FIRDataSnapshot