SwiftUI:如何在Firestore中阅读特定文档? [英] SwiftUI: How can I read a specific document in Firestore?

查看:50
本文介绍了SwiftUI:如何在Firestore中阅读特定文档?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

So I have a "Users" collection in Firestore, and I want to read one of the documents.

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

The document I want to read has a UserUID as its Document ID, so my question is how can I read that document?

非常感谢您的帮助.

这是我当前正在使用的代码:

This is the code I'm currently using:

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

推荐答案

我不确定您是在问一个SwiftUI问题,还是一个Firebase问题,所以我将同时解决这两个部分.

I'm not sure whether you're really asking a SwiftUI question, or just a Firebase question, so I'll address both parts.

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

In terms of getting a specific document from Firebase, you'll want to use a more specific query than getDocuments. Specifically, you can use document() and pass the ID as a parameter:

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

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

(this sample code is based on the Firebase documentation at https://firebase.google.com/docs/firestore/query-data/get-data#swift

不知道您的数据在文档中的结构如何,很难准确地说出 下一步该怎么做,但是如果您想将其属性存储在一个变量中以供使用您的视图中,可以设置一个@State变量:

Having no knowledge about how your data is structured within your document, it's tough to say exactly what to do next, but if you wanted to store a property of it in a variable to be available in your view, you could set a @State variable:

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

您很可能会发现在 Button 回调中存储网络逻辑(例如与Firebase对话)存在一些局限性和陷阱.可能希望考虑使用类似 ObservableObject 的方法来处理这些调用,然后再提供一个 @Published 属性,您可以从视图中访问该属性.

You will most likely find that storing your networking logic (eg talking to Firebase) inside your Button callback has some limitations and pitfalls. Might want to consider something like an ObservableObject that handles these calls and then has a @Published property you can access from your view.

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

A limited example of this would be (note: just a conceptual example -- not tested code):

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

这篇关于SwiftUI:如何在Firestore中阅读特定文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆