Veronika Babii
Veronika Babii

Reputation: 384

How to delete specific document for the current user from Firebase Firestore in swift?

I'm using Firebase Firestore to store collection of tasks.
I want to create following scenario: when user deletes a specific task, it should be removed from tableview and from database only for this current user. But I'm only able to delete the selected task from db at all, not for current user. Please help!

My set up code:

class TasksListScreen: UIViewController {
    var tasksArray = [Task]() // array of tasks via Task struct

    // to load data from db
    func loadData() {
        db.collection("tasks").getDocuments { (queryShapshot, error) in
            if let error = error {
                print("\(error.localizedDescription)")
            } else {
                self.tasksArray = queryShapshot!.documents.flatMap({Task(dictionary: $0.data())})
                // to update user interface
                DispatchQueue.main.async {
                    self.tableView.reloadData()
                }
            }
        }
    }
}

I'm able to delete selected task (document) from my collection at all via this code.

extension TasksListScreen: UITableViewDataSource, UITableViewDelegate {

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {

        // if action is deletion
        if editingStyle == UITableViewCell.EditingStyle.delete {

            let title = tasksArray[indexPath.row].title
            let collectionRef = db.collection("tasks")
            let query : Query = collectionRef.whereField("title", isEqualTo: title)

            query.getDocuments(completion:{ (snapshot, error) in
                if let error = error {
                    print(error.localizedDescription)
                } else {
                    for document in snapshot!.documents {
                        self.db.collection("tasks").document("\(document.documentID)").delete()
                    }
                }
            })

            // delete task from table view
            tasksArray.remove(at: indexPath.row)
            //tableView.reloadData()
            tableView.deleteRows(at: [indexPath], with: .fade)
        }
}

But I need to delete selected document from db only for the current user. I've tried this code.

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {

        // if action is deletion
        if editingStyle == UITableViewCell.EditingStyle.delete {

            // delete task from db for the current user
            let title = tasksArray[indexPath.row].title
            let user = Auth.auth().currentUser
            // access collection of tasks of the current user
            let collectionRef = db.collection("users").document((user?.uid)!).collection("tasks")
            // search for task with needed title
            let query : Query = collectionRef.whereField("title", isEqualTo: title)
            print(title)
            print(query)
            query.getDocuments(completion:{ (snapshot, error) in
                if let error = error {
                    print(error.localizedDescription)
                } else {
                    for document in snapshot!.documents {
                        self.db.collection("users").document((user?.uid)!).collection("tasks").document("\(document.documentID)").delete()
                    }
                }
            })
        }
 }

It deletes task during the current session, but when I run my app again the deleted task appears.

Please help!

Upvotes: 0

Views: 619

Answers (1)

George
George

Reputation: 358

If the document has a field that contains the userId, you can do something like this:

for document in snapshot!.documents {
     if document.userId == user.userId {
         self.db.collection("tasks").document("\(document.documentID)").delete()
}
               }

Upvotes: 1

Related Questions