gpt4 book ai didi

ios - 将 Firebase 文档计数返回为表格行计数

转载 作者:搜寻专家 更新时间:2023-11-01 07:01:16 24 4
gpt4 key购买 nike

我有一个函数可以获取集合中 firestore 文档的计数,我想将此计数用作 TableView 函数 numberOfRowsInSection 的返回值。在从服务器检索计数并使程序崩溃之前调用返回。我相信我需要使用闭包来让返回等待完成,但我不确定如何从闭包中返回一个整数。我对 swift 很陌生,对闭包更陌生。

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 {---}
}
}

关于ios - 将 Firebase 文档计数返回为表格行计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51126524/

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