gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 07:30:14 26 4
gpt4 key购买 nike

来自 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com