ios - 将 Firebase 文档计数作为表行计数返回
问题描述
我有一个函数可以获取集合中 firestore 文档的计数,我想将此计数用作表视图函数 numberOfRowsInSection 的返回值。在从服务器检索计数并使程序崩溃之前调用 return。我相信我需要使用闭包来让返回等待完成,但我不确定如何从闭包中返回一个整数。我对 swift 非常陌生,甚至对 Closures 也很陌生。
func getCount(completion: @escaping (Int) -> (Int)) {
let today = getToday()
let eventsRef = db.collection("users").document("test@test.com").collection(today)
eventsRef.getDocuments() { (querySnapshot, err) in
if let err = err {
print("Error getting documents: \(err)")
} else {
completion((querySnapshot?.count)!)
}
}
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
getCount { (count) in
self.count = count
}
return count!
}
解决方案
您需要设置一个实例数组
var arr = [<#typeHere#>]()
//
返回它的计数
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arr.count
}
并在此处重新加载表格
func getCount(completion: @escaping (Int) -> (Int)) {
let today = getToday()
let eventsRef = db.collection("users").document("test@test.com").collection(today)
eventsRef.getDocuments() { (querySnapshot, err) in
if let err = err {
print("Error getting documents: \(err)")
}
// fill the array here
tableView.reloadData() // if it's a background thread embed code in DispatchQueue.main.async {---}
}
}
推荐阅读
- javascript - 将功能连接到 PC 文件夹中显示的图片
- android - 是否可以让 ndk 的链接器在启用多线程的情况下运行?
- spring - GCP 日志查看器中的重复日志
- python - ValueError:检查输入时出错:预期 lstm_input
- python - 使用多线程/多处理加速抓取
- blazor - .Net Core Blazor - 使用带有 onclick 的输入复选框绑定的 Javascript 错误
- google-cloud-platform - JupyterLab:无法保存笔记本。“文件 > 保存笔记本”灰显。自动保存和 Cmd + S 也不起作用
- c++ - 如何通过 C++ 中的数据库链接执行 Oracle 包
- go - 如何创建两个 udp 套接字,一个发送请求,另一个接收答案?
- python - Python生成器与列表作为数组初始化器