Firebase 如何读取Firestore(Swift)中字段的值

Firebase 如何读取Firestore(Swift)中字段的值,firebase,google-cloud-firestore,swiftui,Firebase,Google Cloud Firestore,Swiftui,我想读取文档中某个字段的值(在带有SwiftUI的Firebase Firestore中)。 我已经拥有的是: let value = myDataBase // My Database instance // value.collection("My Collection").whereField("Code", isEqualTo: codeTextInput) .getDocuments() { (querySnapshot, er

我想读取文档中某个字段的值(在带有SwiftUI的Firebase Firestore中)。 我已经拥有的是:

 let value = myDataBase
 // My Database instance
 //
 value.collection("My Collection").whereField("Code", isEqualTo: codeTextInput)
     .getDocuments() { (querySnapshot, err) in
         if let err = err {
             print("Error getting documents: \(err)")
         } else {
             for document in querySnapshot!.documents {
                 print("\(document.documentID) => \(document.data())")
                                    
             }
        }
   }
(此代码工作正常)

现在,我想存储所有文档的值,这些文档都在我的集合中,并且具有键“Code”的值,该值是键入的。但我想存储密钥“Wert”的数据

当我保存它时,我想将其用作用户默认设置。。。 顺便说一句,我不想用这个代码收集超过1件物品,我只想我收集的物品是正确的。

总结一下:

  • 您希望获取集合中具有特定值的所有文档
  • 您希望保存所有这些值并能够访问它们
  • 在这种情况下,我只能建议使用
    对象
    。让我们举个例子:

    让我们导入所有模块

    import Foundation
    import Firebase
    import FirebaseFirestoreSwift
    import FirebaseStorage
    import Combine
    
    首先,我们声明结构:

    现在,我们访问它并为每个可以获取的文档生成一个对象,其中包含您想要的值:

    var myArray:Array=[]//我们将在其中存储所有对象的空数组
    var codeTextInput=“测试”
    //仅获取所需文档
    设db=Firestore.Firestore()
    让docRef=db.collection(“我的收藏”)。whereField(“Code”,isEqualTo:codeTextInput)
    func getDocumentsAsObjects(){//docRef.getDocuments需要在函数中,否则:不允许在顶级使用表达式
    docRef.getDocuments{(querySnapshot,err)在//getDocuments中与在多个
    如果让err=err{
    打印(“获取文档时出错:\(错误)”)
    }否则{
    对于querySnapshot!中的文档,文档{//迭代它们并将它们添加到数组中
    让结果=结果{
    尝试document.data(如:MyObject.self)
    }
    切换结果{
    成功案例(让我的对象):
    如果让myObject=myObject{
    myObject.id=document!.documentID//获取文档的id,因为我们以后可能需要它
    myArray.append(myObject)//将文档保存到数组中
    }否则{
    //从DocumentSnapshot成功初始化了一个nil值,
    //或者文档快照为零。
    打印(“文档不存在”)
    }
    案例。失败(let错误):
    //无法从DocumentSnapshot初始化'MyObject'值。
    打印(“错误解码城市:\(错误)”)
    }
    }
    }
    }
    }
    

    现在你的数组中有了对象,可以访问它们了

    你能详细说明一下(在你的问题中)你想对这些值做什么吗?是否要对它们进行聚合(例如,求和),将它们显示在列表中…?已完成。我只想说:我不想收集多个值。当我这样做时,我会得到一个错误:“Query”类型的值没有成员“getDocument”,你说得对。我没有检查它是否可以编译。我的回答不好。现在已更正并为我编译。只需简单说明-由于您的所有字段名都与文档中的名称匹配,因此无需使用
    编码键。您还应该使用@DocumentID映射文档ID,这将允许您消除强制展开文档ID(
    myObject.ID=document!.DocumentID
    )。@Boothosh,这是否回答了您的问题?是的,您是对的。我只是保留了示例中的CodingKeys,因为我假设他的文档中不止有1个值。
    public struct MyObject: Codable {
    
        let id: String
        let code: String?
    
        // Needed to identify them in Firestore
        enum CodingKeys: String, CodingKey {
            case id
            case code = "code"
        }
    
    }
    
    var myArray: Array<MyObject> = [] // Empty array where we will store all objects in
    var codeTextInput = "Test"
    
    // Fetch only desired documents
    let db = Firestore.firestore()
    let docRef = db.collection("My Collection").whereField("Code", isEqualTo: codeTextInput)
    
    func getDocumentsAsObjects() { // docRef.getDocuments Needs to be in function or else: Expressions are not allowed at the top level
        docRef.getDocuments { (querySnapshot, err) in //getDocuments (s) as in multiple 
            
            if let err = err {
                print("Error getting documents: \(err)")
            } else {
                for document in querySnapshot!.documents { // iterate them and add them to your array
                    let result = Result {
                        try document.data(as: MyObject.self)
                    }
                    
                    switch result {
                    case .success(let myObject):
                        if let myObject = myObject {
                            myObject.id = document!.documentID // Get the ID of the Document as we might need it later
                            myArray.append(myObject) // Save the document into your array
                        } else {
                            // A nil value was successfully initialized from the DocumentSnapshot,
                            // or the DocumentSnapshot was nil.
                            print("Document does not exist")
                        }
                    case .failure(let error):
                        // A `MyObject` value could not be initialized from the DocumentSnapshot.
                        print("Error decoding city: \(error)")
                    }
                    
                }
            }
        }
    }