如何从documentSnapshot获取值

时间:2019-03-08 11:34:07

标签: swift google-cloud-firestore

我使用Firestore,并具有一个带有字段的集合。该字段具有多个字符串值:

字段:名称

  • 0:“名称1”
  • 1:“名称2”
  • 2:“名称3”

使用

let documentData = documentSnapshot.data()

我得到一个带有1个键(名称)和3个值的字典。

用值获取String数组的最佳方法是什么? (也许有Codable)

我尝试过

if let data = try? JSONSerialization.data(withJSONObject: documentData as Any, options: []) {
   let users = try? JSONDecoder().decode(??.self, from: data)                
}

预先感谢

2 个答案:

答案 0 :(得分:0)

我不确定我的方法是最好的方法,但是让我们尝试一下。

我会做这样的事情:

//Choosing collection
            db.collection("YOUR_COLLECTION").getDocuments()
                    { (QuerySnapshot, err) in
                        if err != nil
                        {
                            print("Error getting documents: \(String(describing: err))");
                        }
                        else
                        {
                            //For-loop
                            for document in QuerySnapshot!.documents
                            {
                                //let document = QuerySnapshot!.documents
                                let data = document.data()

                                let data1 = data["YOUR_DATA1"] as? String
                                let data2 = data["YOUR_DATA2"] as? String

                                //Now you can access your data1 and data2 like this:
                                //example code:
                                txtfield_data1.text = data1
                                txtfield_data2.text = data2
                            }

您可以在此处随意设置格式。 我希望这就是您的意思,否则,请告诉我,我将尽力编辑。 :)祝你有美好的一天!

答案 1 :(得分:0)

我现在已经解决了。可能存在更好的东西。

    let db = Firestore.firestore()
    let userReference = db.collection("users").document(user.uid)

    userReference.getDocument { (documentSnapshot, error) in
        if let error = error {

        } else if let documentSnapshot = documentSnapshot, documentSnapshot.exists {
            if let documentData = documentSnapshot.data() {

                let data = documentData.compactMap({ (arg) -> [String]? in
                    let (_, value) = arg
                    var array = [String]()

                    if let values = value as? [String] {
                        for item in values {
                            array.append(item)
                        }
                    }

                    return array
                })

                let users = data.flatMap({ (value) -> [String] in
                    return value
                })

                print(users)
            }

        } else {

        }
    }