如何在Swift 4.2上从地图(对象)Cloud Firestore文档获取数据? [英] How to get data from a map (object) Cloud Firestore document on Swift 4.2?

查看:38
本文介绍了如何在Swift 4.2上从地图(对象)Cloud Firestore文档获取数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将Cloud Firestore用作iOS应用程序的数据库.

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

当文档包含地图(对象类型)时,我想查询数据时遇到问题.通过简单的查询,我无法访问地图(nameOnId)的字段(例如:firstName).

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.

我的代码如下:

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

我在某处读到,为了能够访问map对象内的值,我需要展平map对象,但是那样不能给我访问它们的权限,我唯一能进入的就是映射中的一组值,因此它仅显示它们的键和值,例如:

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

问题是如何使用查询访问"John"之类的单个值?我在Cloud Firestore上的数据结构

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

推荐答案

一种实现方法如下.同样好的做法是不强制打开您的querySnapshot(如果查询不存在,则您的应用程序将崩溃!).希望这会有所帮助!

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

这篇关于如何在Swift 4.2上从地图(对象)Cloud Firestore文档获取数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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