How to get data from a map (object) Cloud Firestore document on Swift 4.2?

偶尔善良 提交于 2021-02-19 09:11:01

问题


I am using Cloud Firestore as a Database for my iOS App.

I have an issue while I want to query my data when the document contains Maps (Object Type). I can not access the fields (say: firstName here) of a map (nameOnId) by having the simple query.

My code is as bellow:

let db = Firestore.firestore()
    db.collection("userDetails").getDocuments() { (querySnapshot, err) in

        if let err = err {
            print("Error getting documents: \(err)")
        } else {
            for document in querySnapshot!.documents {
                let results = document.data()
                let result2 = results.compactMap({$0})
                print("listedItems: \(document.documentID) => \(result2[0].value)") }}}

I read somewhere that in order to be able to access the values inside the map object, I need to flatten the map object, but having that does not give me access to them, the only thing that I could get into are a group of values inside the map so it only shows the keys and values for them like:

{
firstName = "John";
middleName = "British";
middleName = "Citizen";
gender = "M";
DOB = "8 December 2000 at 00:00:00 UTC+11";
}

the question is how to get access to a single value like "John" using the query?My data structure on Cloud Firestore


回答1:


One way of doing it is as follows. Also its good practice to not force unwrap your querySnapshot (if the query does not exist, your app will crash!). Hope this helps!

let db = Firestore.firestore()
db.collection("userDetails").getDocuments() { (querySnapshot, err) in
    if let err = err {
        print("Error getting documents: \(err)")
    } else if let querySnapshot = querySnapshot {
        for document in querySnapshot.documents {
            let results = document.data()
            if let idData = results["nameOnID"] as? [String: Any] {
                let firstName = idData["firstName"] as? String ?? ""
                print(firstName)
            }
        }
    }
}


来源:https://stackoverflow.com/questions/52916414/how-to-get-data-from-a-map-object-cloud-firestore-document-on-swift-4-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!