简体   繁体   English

Swift:将单个文档映射到 Firebase Firestore 中的结构

[英]Swift: Mapping a single document to a struct within Firebase Firestore

I'm try to map a single Firestore document to a @Published var of my ObservableObject repository class.我正在尝试将单个 Firestore 文档 map 放到我的 ObservableObject 存储库 class 的 @Published var 中。

The struct that the document is mapped to obeys the codable protocol, so this should be straight forward, but I am missing something somewhere, as the document data is not showing in my UI.文档映射到的结构遵循可编码协议,所以这应该是直截了当的,但我在某处遗漏了一些东西,因为文档数据没有显示在我的 UI 中。

class Repository: ObservableObject {
  
  let db = Firestore.firestore()
  
  @Published var documentData: DocumentData?
  
  func getDocumentDataById(id: String) {
    
    db.collection("documentData").document(id)
      .addSnapshotListener { documentSnapshot, error in
        print("fetching")
        if let documentSnapshot = documentSnapshot, documentSnapshot.exists {
          do {
            print("document exists")
            self.documentData = try documentSnapshot.data(as: DocumentData.self)
          } catch {
            print(error)
          }
        }
      }
  }
}

The logs show "fetching", but never progress to show either "document exists" or the error.日志显示“正在获取”,但从未显示“文档存在”或错误。

What am I doing wrong?我究竟做错了什么?

When you use addSnapshotListener to listen to real-time updates, you're attaching a listener that is called for any change that occurs in your database.当您使用addSnapshotListener侦听实时更新时,您将附加一个侦听器,该侦听器会为数据库中发生的任何更改而调用。 As a result, this happens even when your app is ended, which is why detaching the listeners before the activity is killed is required.因此,即使在您的应用程序结束时也会发生这种情况,这就是为什么需要在 Activity 被终止之前分离侦听器的原因。

Here is an example of how you can update your current code:以下是如何更新当前代码的示例:

db.collection(documentData).document(id)
    .addSnapshotListener { documentSnapshot, error in
      guard let document = documentSnapshot else {
        print("Error fetching document: \(error!)")
        return
      } 
      guard let data = document.data() else {
        print("Document data was empty.")
        return
      }
      print("Current data: \(data)")
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM