【问题标题】:Delete element from array in Firebase从 Firebase 中的数组中删除元素
【发布时间】:2021-09-11 17:33:27
【问题描述】:

如何从 firebase 的数组中删除元素?我有两个数组 - 第一个带有名称,第二个带有菜单类型。 使用我的代码,我只从第一个数组中删除。

  func reloadTableView() {
    guestList.removeAll()
    if let tableId = tableData?.id {
        
        Database.database().reference().child("userInfo").child(uid!).child("tables").child(tableId).child("guestsOnTable").queryOrderedByKey().observe(.value) { (snapshot) in
            if snapshot.childrenCount>0 {
                self.guestList.removeAll()
                
                for guest in snapshot.children.allObjects as![DataSnapshot]{
                    if let guestObject = guest.value as? String{
                        self.guestList.append(guestObject)
                    }
                }
                DispatchQueue.main.async {
                    self.guestsOnTableTableView.reloadData()
                }
            }
        }
        
    }
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {

    if editingStyle == .delete {

        let guestName = guestList[indexPath.row]

        if let tableId = tableData?.id{
            refGuests = Database.database().reference().child("userInfo").child(uid!).child("tables").child(tableId).child("guestsOnTable")
            refGuests.observe(.value) { (snapshot, error) in

                if let error = error {
                    print(error.description)
                }
                if let guests = snapshot.children.allObjects as? [DataSnapshot] {

                    for (index,guest) in guests.enumerated() {
                        if let guestObject = guest.value as? String {
                            if guestObject == guestName {
                                self.guestList.remove(at: index)
                                self.refGuests.setValue(self.guestList)
                                DispatchQueue.main.async {
                                    self.guestsOnTableTableView.reloadData()
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

enter image description here

这是从火力基地拍摄的。

【问题讨论】:

    标签: ios arrays swift


    【解决方案1】:

    目前尚不完全清楚您要达到的目标。

    一般来说,您可以使用 FieldValue.arrayRemove 从 Firestore 中的数组中删除元素。 https://firebase.google.com/docs/reference/android/com/google/firebase/firestore/FieldValue

    查看示例 How to delete object from array in firestore

    【讨论】:

      猜你喜欢
      • 2011-10-31
      • 1970-01-01
      • 2020-04-28
      • 2022-01-13
      • 2016-03-08
      • 2017-09-13
      • 2017-12-22
      • 1970-01-01
      相关资源
      最近更新 更多