简体   繁体   中英

Removing child data from Firebase Database Swift 3

Please help me if possible. I want to remove data in the tableView when user calls the delete editingStyle function using the removeValue method. So far I have a class for the item:

class Item : NSObject {

    var itemName: String!
    var itemDate: String!
    var itemID: String!

    init(itemName: String, itemDate: String, itemID: String) {

        self.itemName = itemName
        self.itemDate = itemDate
        self.itemID = itemID



    }

    init(snapshot: FIRDataSnapshot) {

        let snapshotValue = snapshot.value as? NSDictionary

        self.itemName = snapshotValue!["itemName"] as! String
        self.itemDate = snapshotValue!["itemDate"] as! String
        self.itemID = snapshotValue!["itemID"] as! String
    }

        func toAnyObject() -> [String: AnyObject] {
            return ["itemName": itemName as AnyObject, "itemDate": itemDate as AnyObject, "itemID": itemID as AnyObject]
    }


}

Now I want to delete the values inside the users itemID but I'm not sure where to go from here:

override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {

    guard let uid = FIRAuth.auth()?.currentUser?.uid else {
        return
    }

    let item = itemArray[indexPath.row]
    let itemID = databaseRef.child("ItemID")

    databaseRef.child("users").child(uid).child("usersList").child(itemID).removeValue()

I think you're missing the "delete" editing style & the reference needed a little change. Try this:

override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {

    guard let uid = FIRAuth.auth()?.currentUser?.uid else {
        return
    }

    let item = items[indexPath.row]
    let itemID = ref.child("users").child(uid).child("usersList").child("ItemID")

    if editingStyle == .delete {
        item.ref?.removeValue()
    }

}

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