从UITableView删除带有ChildByAutiID的数据

时间:2019-07-01 11:34:02

标签: swift firebase uitableview

我正在制作一个应用程序,其中的一项功能使用户可以创建列表。列表以UITableView的形式显示,我希望能够通过滑动从列表中删除项目。 我正在从按下按钮时显示的UIViewController向Firebase添加数据。

添加数据的代码:

导入UIKit 导入Firebase

class AddListItemViewController: UIViewController {

    var doneSaving: (() -> ())?

    var ref:DatabaseReference?
    var databaseHandle:DatabaseHandle?

    override func viewDidLoad() {
        super.viewDidLoad()

        ref = Database.database().reference()

    }


    @IBAction func cancelButtonTapped(_ sender: Any) {

        dismiss(animated: true, completion: nil)
    }

    @IBAction func saveButtonTapped(_ sender: Any) {

        let userID = Auth.auth().currentUser?.uid

        let refKey =  self.ref?.child("userDatabases").child(userID!).child("lists").childByAutoId()

        let refID = refKey?.key

        refKey?.setValue(["listName" : newListName, "listID" : refID])

        if let doneSaving = doneSaving {
            doneSaving()
        }

            dismiss(animated: true, completion: nil)

    }
   }     

在显示数据的ViewController中,我执行以下操作:
我在viewDidLoad中调用此函数以读取数据:

func getData() {

        let userID = Auth.auth().currentUser?.uid
               ref?.child("userDatabases").child(userID!).child("lists").observe(DataEventType.value, with: { (snapshot) in
            for child in snapshot.children.allObjects as! [DataSnapshot] {
                // print(child.value)
                let dict = child.value as? [String : AnyObject] ?? [:]

                self.userLists.append(dict["listName"] as! String)
                self.listID.append(dict["listID"] as! String)

               print(self.userLists)
                print(self.listID)

                self.tableView.reloadData()
            }
        })    
}    

要删除,我在做:

func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        let delete = UIContextualAction(style: .destructive, title: "Delete List") { (contextualAction, view, actionPerformed: (Bool) -> Void) in


            let userID = Auth.auth().currentUser?.uid

            let deleteRow = self.userLists[indexPath.row]

           self.ref?.child("userDatabases").child(userID!).child("lists").child(self.listID[indexPath.row]).removeValue(completionBlock: { (error, ref) in


                    if error == nil {

                        self.userLists.removeAll()
                        self.getData()
                        tableView.reloadData()

                        print(deleteRow)
                    } else {
                        print("Error deleting", error!)
                        return
                    }
                })

        }
        delete.image = #imageLiteral(resourceName: "Delete")

        return UISwipeActionsConfiguration(actions: [delete])
    }    

最后要在doneSaving中使用AddListItemViewController函数,我正在这样做:

 override func prepare(for segue: UIStoryboardSegue, sender: Any?)
    { 
   if segue.identifier == "ToAddListItemVCSegue" {
            let destination = segue.destination as! AddListItemViewController
            destination.doneSaving = { [weak self] in
                self?.userLists.removeAll()
                self?.listID.removeAll()
                self?.tableView.reloadData()

            }
        }
    }    

Firebasestructure:

  "userDatabases" : {
    "fROjFkxrj8UTmBiUxjF6Pdc5xYY2" : {
      "lists" : {
        "-Ligy-aARpjNYKMOktwx" : {
          "listID" : "-Ligy-aARpjNYKMOktwx",
          "listName" : "Test4"
        },
        "-Ligy76d3H5T_kybdhf8" : {
          "listID" : "-Ligy76d3H5T_kybdhf8",
          "listName" : "Test1"
        }
      }
    }
   }    

这在某种程度上是可行的,但是在进行一些添加和删除后,数据似乎不同步。

如何最好地将tableViewRow与Firebase中的ID链接起来?

0 个答案:

没有答案