【问题标题】:SwiftUI: How can I read a specific document in Firestore?SwiftUI:如何阅读 Firestore 中的特定文档?
【发布时间】:2021-01-21 00:40:45
【问题描述】:

所以我在 Firestore 中有一个“用户”集合,我想阅读其中一个文档。

我要阅读的文档有一个 UserUID 作为其文档 ID,所以我的问题是如何阅读该文档?

非常感谢您的帮助。

这是我目前使用的代码:

Button(action: {
    guard let userID = Auth.auth().currentUser?.uid else { return }
    Firestore.firestore().collection("Users").getDocuments() { (querySnapshot, err) in
        if let err = err {
            print("Error getting documents: \(err)")
        } else {
            for document in querySnapshot!.documents {
                print("\(document.documentID) =>  \(document.data())")
            }
        }
    }
}) {
    Text("Read Data From DataBase")
}

【问题讨论】:

    标签: ios database firebase swiftui


    【解决方案1】:

    我不确定您是真的在问一个 SwiftUI 问题,还是只是一个 Firebase 问题,所以我将解决这两个部分。

    就从 Firebase 获取特定文档而言,您需要使用比 getDocuments 更具体的查询。具体可以使用document(),并将ID作为参数传递:

    Firestore.firestore().collection("Users").document(userID).getDocument { (document, error) in
        if let document = document, document.exists {
            let dataDescription = document.data().map(String.init(describing:)) ?? "nil"
            print("Document data: \(dataDescription)")
            let fieldValue = document.get("myFieldName") as? Int
            let fieldValueType2 = document.data()["myFieldName"] as? Int
        } else {
            print("Document does not exist")
        }
    }
    

    (此示例代码基于位于 https://firebase.google.com/docs/firestore/query-data/get-data#swift 的 Firebase 文档

    不了解文档中数据的结构,很难确切地说明下一步该做什么,但如果您想将其属性存储在一个变量中,以便在你的观点,你可以设置一个@State 变量:

    struct MyView : View {
      @State var myData : String = ""
      
      ...
      //in your firebase callback:
      myData = someDataFromTheFirebaseDocument
    }
    

    您很可能会发现在Button 回调中存储您的网络逻辑(例如与Firebase 对话)有一些限制和陷阱。可能需要考虑处理这些调用的 ObservableObject 之类的东西,然后您可以从视图中访问 @Published 属性。

    一个有限的例子是(注意:只是一个概念性的例子——未经测试的代码):

    struct MyView {
      @ObservedObject var firebaseConnector = FirebaseConnector()
    
      var body : some View {
        VStack {
          Button(action: { firebaseConnect.apiCall() }) {
            Text("Press me")
          } 
          Text("Firebase data: \(firebaseConnector.dataToDisplay)")
        }
      }
    }
    
    class FirebaseConnector : ObservableObject {
      @Published var dataToDisplay : String
    
      func apiCall() {
        guard let userID = Auth.auth().currentUser?.uid else { return }
        Firestore.firestore().collection("Users").document(userID).getDocument { (document, error) in
        if let document = document, document.exists {
            let dataDescription = document.data().map(String.init(describing:)) ?? "nil"
            self.dataToDisplay = dataDescription
        } else {
            print("Document does not exist")
        }
       }
      }
    }
    
    

    【讨论】:

    • 感谢您提供的详细答案,这确实很有帮助。但是如何在不知道该特定字段的值的情况下提取文档中的特定字段? @jn_pdx
    • 我更新了我的第一个代码示例,其中包含如何查询某个字段的示例。 document.data() 返回一个 [String:Any] 字典,因此您可以使用该字典或使用 document.get() 获取字段值。如果答案对您有所帮助,请考虑支持/接受
    • 再次感谢它完美运行。我的另一个问题是,在检索文档后,我如何遍历所有字段值并对它们进行处理?就像存储了图像一样,我将如何遍历它们,然后显示每个图像? @jn_pdx
    • document.data() 会给你一个Dictionary 类型为[String:Any]。您可以使用类似的方式对其进行迭代:stackoverflow.com/questions/24111627/…
    • 所以我查看了堆栈链接,但我不确定如何迭代文档中的值。你可以给我看看吗?真的很感激@jn_pdx
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-26
    • 1970-01-01
    • 2019-06-26
    • 2019-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多