swift - FireStore swift : Accessing counts and document details for use in a table

标签 swift firebase google-cloud-firestore

来自 FireStore Swift 4 : How to get total count of all the documents inside a collection, and get details of each document? 的代码在我的 TableViewController 的 viewDidLoad 部分调用时正确打印到控制台。但是,我尝试对行数使用“计数”,并挑选出一些文档详细信息以显示在表格中。

我现在遇到的问题是,这些详细信息似乎锁定在此 QuerySnapshot 调用中,我无法在 numberOfRowsInSection 和 CellForRowAt 中访问它们。我正在使用 xcode 版本 10。抱歉,如果这是一个菜鸟问题,但我已经被难住了一段时间。

var count = 0
override func viewDidLoad() {
    super.viewDidLoad()

    let reviewTopic = Firestore.firestore().collection("usersIds").document(userEmail!).collection("reviews")
    reviewTopic.getDocuments() {
        (QuerySnapshot,err) in

        if let err = err {
            print("Error getting documents: \(err)");
        } else {
            for document in QuerySnapshot!.documents {
                self.count += 1
                print("\(document.documentID) => \(document.data())");
            }
            print("Count = \(self.count)"); 
        }
        print("Count from viewDidLoad: ", self.count) // prints 2
    }
}

同样,上面返回了正确的计数 (2) 和文档详细信息,但我试图使用 numberOfRowsInSection 中的值,它在 viewDidLoad 之前运行并返回 0。

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    print("Count from numrows: ", self.count)
    return self.count //returns value of 0
}

最佳答案

从服务器获取数据后,您忘记重新加载 UITableView,因此您需要重新加载 UITableView:

self.tableView.reloadData()

for 循环之后。因为这是一个异步调用,您需要等待直到从服务器获取数据。

您的代码将如下所示:

override func viewDidLoad() {
    super.viewDidLoad()

    let reviewTopic = Firestore.firestore().collection("usersIds").document(userEmail!).collection("reviews")
    reviewTopic.getDocuments() {
        (QuerySnapshot,err) in

        if let err = err {
            print("Error getting documents: \(err)");
        } else {
            for document in QuerySnapshot!.documents {
                self.count += 1
                print("\(document.documentID) => \(document.data())");
            }
            print("Count = \(self.count)"); 
            self.tableView.reloadData()
        }
        print("Count from viewDidLoad: ", self.count) // prints 2
    }
}

您还应该创建一个类对象并将所有数据存储到一个类对象中,然后将该数据访问到您的cellforrownumberofrows 方法中。或者您可以使用 Codable 协议(protocol)从服务器解析您的 JSON 并存储服务器数据。

有了它,您可以轻松管理您的 UITableView 数据源,您还可以轻松找出哪个单元格被按下。

关于swift - FireStore swift : Accessing counts and document details for use in a table,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55015760/

相关文章:

swift - 扫描信标并 swift 找到最近的信标

ios - 安装失败 'cordova-plugin-firebase-authentication' : undefined

firebase - Firestore 中数组的存储大小限制是什么?

android - 从 Android 应用调用 sendFollowerNotification Firebase 函数

javascript - 在 javascript 中使用 firebase firestore 更新功能中的 promise

google-cloud-platform - 如何从谷歌云Firestore下载大量文件?

android - 如何不在 Flutter 的 Firebase firestore 中保存等于字符串

ios - 使用 Alamofire 将图像上传到服务器不起作用

json - 数据未被搜索栏过滤

ios - 从两点创建大括号曲线