簡體   English   中英

在 Firestore 中收聽一個添加的文檔 - Swift

[英]Listening to one added document in Firestore - Swift

我只聽一個集合中添加的文檔,閱讀后我需要刪除該文檔。 這是我實現的代碼:

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()
                }
            }
        })
    })
}

問題是文件被刪除后

更改.document.reference.delete()

即使文檔已被刪除,偵聽器片段change.type ==.added也會被觸發。 我不知道為什么...

我如何才能只收聽 Firestore 集合中實際添加的文檔?

編輯:

偵聽特定文檔但在刪除文檔時仍調用閉包:

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()
        }
    })

我只聽了一個集合中添加的文檔。

不你不是。 您將快照偵聽器附加到集合而不是單個文檔:

db.collection("Collection")
  .document(currentUid)
  .collection("Collection") //👈
  .addSnapshotListener(/* ... */)

這意味着您正在偵聽在稱為“集合”的整個子集合中發生的每個操作的實時更新。

你基本上在做什么,你在說,嘿 Firestore,給我那個子集合中存在的所有文檔,讓聽眾保持活力。 每當該集合中的文檔隨時間發生變化時,都會調用此偵聽器。

如果您想收聽單個文檔,則應添加對.document()的調用並傳遞特定的文檔 ID:

db.collection("Collection")
  .document(currentUid)
  .collection("Collection")
  .document("someDocumentId") //👈
  .addSnapshotListener(/* ... */)

這樣,您只會收到有關單個文檔更改的通知。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM