CodingForFun333
CodingForFun333

Reputation: 55

Delete document from cloud firestore

I am trying to implement a function that allows the user to delete chats that they have with other users.

At the moment the code works and the firestore document is deleted successfully however as soon as the delete happens the code crashes and i get this error "Fatal error: Unexpectedly found nil while unwrapping an Optional value" next to the id = data!["id"] in the code. I guess that after the delete happens firestore keeps listening for documents and finds an empty collection following the delete. Does anyone know how to stop this from happening?

  public func deleteConversation(conversationId: String, completion: @escaping (Bool) -> Void) {
    // Get all conversations for current user
    
    let CurrentUser = Auth.auth().currentUser?.uid
    let db = Firestore.firestore()
    
    let ConversationRef = db.collection("users").document(CurrentUser!).collection("conversations").document(test!)
    
    print("deleting conversation with \(test!)")
    
    ConversationRef.addSnapshotListener { snapshot, error in
        guard let document = snapshot else {
            print("Error getting documents: \(String(describing: error))")
            return
        }
        let data = document.data()
        if let id = data!["id"] as? String, id == conversationId {
            print("conversation found")
            ConversationRef.delete()
       }
        completion(true)
        print("deleted conversation")
    }
    
}

Upvotes: 0

Views: 347

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598728

The problem comes from:

ConversationRef.addSnapshotListener { snapshot, error in

By calling addSnapshotListener you're adding a listener that:

  1. Gets the document snapshot straight away,
  2. Continues listening for changes and calls your code again then there are any.

The problem is in #2, as it means your code executes again when the document is deleted, and at that point document.data() will be nil.

The simplest fix is to only read the document once:

ConversationRef.getDocument { (document, error) in

Upvotes: 3

Related Questions