快速将Firestore中的值分配给变量

时间:2019-03-08 03:02:24

标签: swift firebase google-cloud-firestore

在从实时数据库切换到Firestore的过程中,我已经花了好几个小时的时间,我试图找出一种方法来分配多个文档中的字段(每个文档都包含一张照片和标题)在应用程序中显示时,到目前为止,我的代码看起来像是3岁的孩子,只是在键盘上发脾气,但是对执行此操作的任何帮助将不胜感激。

我已经阅读了数百遍文档,并且在这里基本上阅读了StackOverflow上所有类似的问题,但是没有任何作用。

P.S。我还没睡超过36个小时。

        db.collection("posts").addSnapshotListener { (querySnapshot, error) in
        // get the data of all the documents into an array
        var data = querySnapshot.docs.map(function (documentSnapshot) {
            return documentSnapshot.data();
        });
    }

1 个答案:

答案 0 :(得分:1)

这是您尝试执行的操作的非常简化的版本。拥有数据后,您可以像下面的示例一样分别解包它们,或将它们映射到自定义Swift对象。但是看来您的问题只是关于从Firestore获取数据,这就是您将如何执行此操作:

featuredAttractionsQuery.addSnapshotListener { (snapshot, error) in

    guard let snapshot = snapshot,
        error == nil else { // error

            if let error = error {
                print(error.localizedDescription)
            }
            return // terminate query

    }

    guard !snapshot.isEmpty else { // no data
        return // terminate query
    }

    // data fetched
    for doc in snapshot.documents {

        guard let caption = doc.get("caption") as? String,
            let imagePath = doc.get("imagePath") as? String else {
                continue // continue loop
        }

        // do something with the data
        // perhaps take the image path and download the image (use a dispatch group if you do)

    }

    // whatever you do, when you're done, load your data source

}

还有很多事情要做,例如使用调度队列(在后台解析数据)和调度组(处理异步返回的图像下载)。