Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/kubernetes/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift 如何从tableview中删除单元格_Swift_Firebase_Uitableview_Google Cloud Firestore - Fatal编程技术网

Swift 如何从tableview中删除单元格

Swift 如何从tableview中删除单元格,swift,firebase,uitableview,google-cloud-firestore,Swift,Firebase,Uitableview,Google Cloud Firestore,我正在尝试从tableview和Firestore中删除单元格。 以下是我如何声明我的购物车: struct Cart { var photoKeyCart: String var foodCart: String var priceCart: Int } var cart: [Cart] = [] // This is in the cart controller 这是我的tableview,其中有我的购物车项目: extension CartViewContro

我正在尝试从tableview和Firestore中删除单元格。 以下是我如何声明我的购物车:

struct Cart
{
    var photoKeyCart: String
    var foodCart: String
    var priceCart: Int
}

var cart: [Cart] = [] // This is in the cart controller

这是我的tableview,其中有我的购物车项目:

extension CartViewController: UITableViewDelegate, UITableViewDataSource
{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        var sum = 0
        
        for item in cart{
            sum += item.priceCart
        }
        
        priceTotalLabel.text = "\(sum) lei"
        return cart.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = cartTableView.dequeueReusableCell(withIdentifier: "CartTableViewCell", for: indexPath) as! CartTableViewCell
        let carts = cart[indexPath.row]
        let storageRef = Storage.storage().reference()
        let photoRef = storageRef.child(carts.photoKeyCart)
        
        cell.foodInCartPrice.text = " \(carts.priceCart) lei "
        cell.foodInCartName.text = carts.foodCart
        cell.foodInCartImage.sd_setImage(with: photoRef)
        cell.foodInCartImage.layer.borderWidth = 1
        cell.foodInCartImage.layer.masksToBounds = false
        cell.foodInCartImage.layer.borderColor = UIColor.black.cgColor
        cell.foodInCartImage.layer.cornerRadius = cell.foodInCartImage.frame.height/2
        cell.foodInCartImage.clipsToBounds = true
        
        return cell
        
    }
这就是我从Firestore获取数据到购物车的方式。这是在视图did load中调用的

func getCartProducts() {
        
        let db = Firestore.firestore()
        let userID = (Auth.auth().currentUser?.uid)!
        db.collection("CartDatabase").document(userID).collection("CartItems").getDocuments {  (document, error) in
            if let error = error {
                print(error)
                return
            } else {
                for document in document!.documents {
                    let data = document.data()
                    let newEntry = Cart(photoKeyCart: data["photoKeyCart"] as! String, foodCart: data["foodCart"] as! String , priceCart: data["priceCart"] as! Int
                    )
                    
                    
                    
                    
                    self.cart.append(newEntry)
                }
            }
            DispatchQueue.main.async {
                //  self.datas = self.filteredData
                self.cartTableView.reloadData()
            }
        }
    }
这就是我试图从tableview和Firestore中删除单元格的方式

func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }
    
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        
        
        let carts = cart[indexPath.row]
        let storageRef = Storage.storage().reference()
        let photoRef = storageRef.child(carts.photoKeyCart)
        
        photoRef.delete { error in
            if let error = error {
                print(error.localizedDescription)
            } else {
                print("File deleted successfully")
            }
        }
        
        
        
     
        let db = Firestore.firestore()
        let userID = (Auth.auth().currentUser?.uid)!
        db.collection("CartDatabase").document(userID).collection("CartItems").getDocuments {  (document, error) in
            if let error = error {
                print(error.localizedDescription)
            } else {
                for document in document!.documents {
                    //print("\(document.documentID) => \(document.data())")
                    db.collection("CartDatabase").document(userID).collection("CartItems").document(document.documentID).delete()
                    //self.db.collection("users").document((user?.uid)!).collection("children").document("\(document.documentID)").delete()
                }
            }}
        
        
        
      
        cart.remove(at: indexPath.row)
        tableView.deleteRows(at: [indexPath], with: .fade)
        
    }
}

我有以下问题。当我尝试删除单元格时,它会工作,但当我关闭购物车并再次返回购物车时,它会删除购物车中的所有项目,而不仅仅是我尝试删除的项目

我想要实现的是:只删除选定的单元格。 帮助:D

更新: 我有一个包含食物的桌面视图,每个细胞都是不同的食物之王。我有一个加号按钮,当点击加号按钮时,我会将食物数据发送到Firestore,然后在购物车中检索数据

这是我向购物车发送数据的方式:

    func updateDocument(collection: String, newValueDict: [String : Any], completion:@escaping (Bool) -> Void = {_ in }) {
        
                    
                     let db = Firestore.firestore()
        let userID = (Auth.auth().currentUser?.uid)!
        db.collection(collection).document(userID).collection("CartItems").document().setData(newValueDict, merge: true){ err in
                        if let err = err {
                            print("Error writing document: \(err)")
                            completion(false)
                            
                        }else{
                            
                            completion(true)
                          
                           
                        }
                    }
                     
                 }
当我点击手机时:

cell.didTapButton = {
            
            self.updateDocument(collection: "CartDatabase",newValueDict: ["foodCart" : mancare.foodName, "photoKeyCart": mancare.photoKeyRestaurant, "priceCart": mancare.priceFood])
           
        }
检查照片

如果没有看到所有的代码,很难提供一个具体的示例,但让我从较高的层次介绍一下

假设我们有一个posts类对象

class PostsClass {
   var docId = ""
   var post = ""
}
和一个类数组(也称为“数据源”)来存储它们

var postsArray = [PostsClass]()
第一步是从Firebase加载所有帖子,在每个类中存储docId和post文本,然后将该类存储在dataSource数组中

myFirebase.getDocuments { doc...
   for doc in documents { //iterate over the documents and populate the array
      let post = PostClass(populate with data from firebase)
      self.postsArray.add(post)
   }
}
dataSouce数组将如下所示

postsArray[0] = some post
postsArray[1] = another post
等等,所有这些都显示在表视图中

然后,用户决定删除第1行的帖子。因此,他们滑动第一行,触发tableView委托事件,让应用程序知道滑动行的索引

步骤1:然后根据扫描的行索引从数组中获取该帖子

let postToDelete = self.postsArray[swiped index]
let docIdToDelete = postsToDelete.docID
步骤2:然后将其从阵列中移除

self.postsArray.deleteRow(atIndex: swiped index)
步骤3:然后将其从Firebase中删除

self.my_firebase.collection("posts").document(docIdToDelete).delete {....

请注意,
func tableView:tableView:commit editingStyle
将在假定删除行时显示
.delete
的编辑样式,并在
indexPath.row

中提供索引,您不需要
DispatchQueue.main.async{
在Firebase闭包中。UI调用总是在主线程上完成;网络连接是在后台线程上完成的。为什么要从Firebase获取文档然后删除它们?这浪费了大量带宽。所以,这就是问题所在@Jay?不。请看我更新的评论。我认为从Firebase读取数据时存在总体设计问题,每个文档都将有一个documentId,它应该是Cart对象以及CartItems的属性。当用户删除cartItem时,您将知道他们选择删除哪一行,然后可以从您的数据源中获取该对象。然后您将拥有documentId,并可以从数组中删除它(通过索引)并通过该文档ID将其从Firebase中删除。@Jay,谢谢Jay的回复。我现在在家,可以尝试其他方法使其正常工作。因此,我需要在我的购物车结构中添加一个文档ID,并在Firebase中的CartItems中添加该文档ID。之后,我需要对代码做哪些更改?