I want to delete the firestore document when I delete the tableView cells, but I don't know how to get the document ID.

Asked 1 years ago, Updated 1 years ago, 408 views

I am currently creating a password management application.
I was able to add the entered value to the firestore and display it in TableView.
Next, we are working on the ability to delete selected TableView cells, and we would like to delete the firestore data (documents) at that time.

I tried writing the code to delete the document as per the official document, but I don't know how to get the document ID.

import UIKit
import Firebase

class MypageViewController:UIViewController, UITableViewDelegate{
    
    
    var displayData: Data = [ ]
    
    let db = Firestore.firestore()
    
    @IBOutlet weak variableView:UITableView!
    @IBOutlet weak var emailLabel: UILabel!
    override func viewDidLoad(){
        super.viewDidLoad()
        
        tableView.delegate=self
        tableView.dataSource=self
        self.tableView.register (UITableViewCell.self, forCellReuseIdentifier: "Cell")
        emailLabel.text=Auth.auth().currentUser?.email
        db.collection("passwordData").getDocuments(){(querySnapshot,err)in
            iflet err=err{
                print("Error getting documents:\(err)")
            } else{
                US>for doc in querySnapshot!.documents{
                    let data = doc.data()
                    if let recorder=data["recorder"]as? String, let service=data["service"] as ? String, let password = data ["password"] as ? US>String{
                        if recorder==Auth.auth().currentUser?.email{
                            let cellData=Data(title:service, password:password,recorder:recorder)
                            self.displayData.append(cellData)
                            print(self.displayData)
                            DispatchQueue.main.async {
                                self.tableView.reloadData()
                                let indexPath=IndexPath(row:self.displayData.count-1, section:0)
                                self.tableView.scrollToRow (at:indexPath, at: .top, animated:true)
                            }
                        }
                    }
                    
                }
            }
        }
    }
    
    func selectRow(at indexPath:IndexPath?, animated:Bool, scrollPosition:UITableView.ScrollPosition){
        print(indexPath)
        print("Selected")
    }
    
}

extension MypageViewController:UITableViewDataSource{
    functableView(_tableView:UITableView, numberOfRowsInSection section:Int) - > Int{
        return self.displayData.count
    }

    functableView(_tableView:UITableView, cellForRowAtindexPath:IndexPath) - >UITableViewCell{
        let passwords = displayData [indexPath.row]
        
//        letcell=tableView.dueReusableCell(withIdentifier: "Cell", for:indexPath)
        letcell=UITableViewCell (style:.subtitle, reuseIdentifier: "Cell")
        cell.textLabel?.text=passwords.password
        cell.detailTextLabel?.text=passwords.title
        return cell
    }
    
    functableView(_tableView:UITableView, canEditRowAtindexPath:IndexPath)->Bool
        {
            return true
        }
    functableView(_tableView:UITableView, commit editingStyle:UITableViewCell.EditingStyle, forRowAtindexPath:IndexPath){
        
        let id: Data=self.displayData [indexPath.row]
        
        
        ifeditingStyle==UITableViewCell.EditingStyle.delete{
            displayData.remove(at:indexPath.row)
            tableView.deleteRows (at: [indexPath as IndexPath], with: UITableView.RowAnimation.automatic)
            db.collection("displayData").document("Could you tell me how to get this ID?US>") .delete() {errin
                iflet err=err{
                    print("Error removing document:\(err)")
                } else{
                    print("Document successfully removed!")
                }
                print(id)
            }

        }
    } 
}

The data you entered has been added to the firestore with the following code:

structure Data{
    variable —String
    var password:String
    var recorder:string
}

iflet title=titleText.text, let password=diaryText.text, let account=Auth.auth().currentUser?.email{
            var ref —DocumentReference?=nil
            ref=db.collection("passwordData").addDocument(data:[
                "recorder": account,
                "service"—title,
                "password": password,
            ]) {errin
                iflet err=err{
                    print("Error adding document:\(err)")
                } else{
                    print("successfully!")
                }
            }
        }

swift xcode firebase

2022-09-30 21:56

1 Answers

It is certainly easy to add properties representing documentID to the data type representing each document (for you, Data and the definition of exactly the same type name in Swift's standard library can be boring.

Your code doesn't seem to use the "custom object" feature that you can use when you import the FirebaseFirestoreSwift module, so you just need to get the documentID and set it to the properties you want.

struct PasswordData{
    var documentID:String
    variable —String
    var password:String
    var recorder:string
}
db.collection("passwordData").getDocuments(){(querySnapshot,err)in
            iflet err=err{
                print("Error getting documents:\(err)")
            } else{
                US>for doc in querySnapshot!.documents{
                    let documentID = doc. documentID//<-
                    let data = doc.data()
                    if let recorder=data["recorder"]as? String,
                       let service = data ["service" ] as ? String,
                       let password=data["password"]as? String
                    {
                        if recorder==Auth.auth().currentUser?.email{
                            letcellData=PasswordData(
                                documentID — documentID,//<-
                                title:service,
                                password:password,
                                recorder:recorder)
                            //...
                        }
                    }
                }
            }
        }

If you do this, simply remove the documentID from the elements that will be deleted during deletion.

let removed=displayData.remove(at:indexPath.row)
        let documentID = removed.documentID
        //... Delete using `documentID`


2022-09-30 21:56

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.