【问题标题】:Assigning values from Firestore to variables in swift在 swift 中将值从 Firestore 分配给变量
【发布时间】:2019-03-08 03:02:24
【问题描述】:

在从实时数据库切换到 Firestore 期间,我一直在努力解决几个小时的问题,我正在尝试找出一种方法来为多个文档(每个文档包含一张照片和一个标题)分配字段显示在应用程序中,我的代码现在看起来像一个 3 岁的孩子刚刚在键盘上发脾气,但任何关于如何做到这一点的帮助将不胜感激。

我已经阅读了数百次文档,基本上在 StackOverflow 上阅读了所有类似的问题,但没有任何效果。

附:我已经超过 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();
        });
    }

【问题讨论】:

    标签: swift firebase google-cloud-firestore


    【解决方案1】:

    这是您尝试做的一个非常简化的版本。一旦你掌握了数据,你可以像下面的例子一样单独解开它们,或者将它们映射到自定义的 Swift 对象。但您的问题似乎只是关于从 Firestore 获取数据。

    featuredAttractionsQuery.addSnapshotListener { (snapshot, error) in
        guard let snapshot = snapshot else { // unable to get snapshot
            if let error = error {
                print(error)
            }
            return // terminate query
        }
        guard !snapshot.isEmpty else { // snapshot is empty
            print("snapshot is empty")
            return // terminate query
        }
        for doc in snapshot.documents { // iterate through documents
            guard let caption = doc.get("caption") as? String,
                let imagePath = doc.get("imagePath") as? String else {
                    continue // if we can't get these two values,
                             // move to next iteration and continue loop
                             // calling return here would exit the function
            }
            // do something with this document's data
            // most likely you'll parse it into a native object
            // and add it to an array
        }
    
        // the loop is complete, reload the table view or collection view
    }
    

    还有很多其他内容,例如使用调度队列在后台解析您的数据,以及使用调度组来处理异步返回的图像下载。但这是几乎所有解析都基于的基本起点。

    【讨论】:

    • 谢谢!你已经为我解决了这个问题,我已经为这个问题敲了几个小时的键盘:)
    • 别打你的头,开始在这里发帖吧?
    • @user1968625 这是一个非常好的答案;它保护代码并且是正确的。需要考虑的一个问题是,如果节点不包含 caption 键,则不会读入该节点。还有guardlet 语句的混合。另一种选择是使用 nil 合并来保护代码并在找不到键时设置默认值。这样代码就会受到保护,如果某些数据存在,它仍然会被检索到。所以 vars 会像这样分配 let caption = doc.get("caption") as? String ?? "No Caption" 和 `let imagePath = doc.get("imagePath") as?细绳 ?? “没有路径”
    猜你喜欢
    • 1970-01-01
    • 2021-01-18
    • 2019-01-16
    • 1970-01-01
    • 1970-01-01
    • 2010-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多