I'm listening to only one added document in a collection, and after it is read I need this document to be deleted. This is the code I implemented:
func createListener(){
guard let currentUid = Auth.auth().currentUser?.uid else { return }
listener = db.collection("Collection").document(currentUid).collection("Collection").addSnapshotListener({ listenerSnapshot, error in
if let error = error{
print(error.localizedDescription)
return
}
listenerSnapshot?.documentChanges.forEach({ change in
if change.type == .added{
let data = change.document.data()
let myview = MYView(data: data)
guard let window = UIApplication.shared.windows.last else { return }
myview.present(to: window) {
change.document.reference.delete()
}
}
})
})
}
The problem is that after the document is deleted with
change.document.reference.delete()
The listener snippet change.type == .added
is triggered even if the document has been deleted. I don't know why...
How can I only listen for actually ADDED documents in a Firestore Collection?
EDIT:
listening for a specific document but still closure called when document is deleted:
listener = db.collection("Collection").document(currentUid).addSnapshotListener({ listenerSnapshot, error in
if let error = error{
print(error.localizedDescription)
return
}
guard let data = listenerSnapshot?.data() else { return }
let myview = MYView(data: data)
guard let window = UIApplication.shared.windows.last else { return }
myview.present(to: window) {
listenerSnapshot?.reference.delete()
}
})
CodePudding user response:
I'm listening to only one added document in a collection.
No, you're not. You're attaching a snapshot listener to a collection and not to a single document:
db.collection("Collection")
.document(currentUid)
.collection("Collection") //