ios - How can I count the documents from a firestore query in swift?
问题描述
The answer must be staring at me but I can't see it. I am trying to query firestore and to get the number of documents it identifies so that I may feed that into my TableView (number of rows) function. Somehow the counter works inside the for loop and I would expect the variable to hold that incremented value but it reverts back to zero when I pass it back. Is it a scope issue ? What am I missing ? here is my code:
func runQueryForNumberOfGames() -> Int {
var counter = 0
// query the games for the user who is logged into app
let currentUid = Auth.auth().currentUser!.uid
db.collection("games").whereField("userTrackingGame", isEqualTo: currentUid).getDocuments { (querySnapshot, err) in
if let err = err {
print("error getting documents: \(err)")
return
}
else {
for document
in querySnapshot!.documents {
print(document)
counter += 1
print("the counter is: \(counter)")
}
}
}
print("the counter outside of the for loop is \(counter)")
return (counter)
}
解决方案
Its async function so you need to return completion handler
func runQueryForNumberOfGames(completion: @escaping (Int?)-> Void) {
var counter = 0
// query the games for the user who is logged into app
let currentUid = Auth.auth().currentUser!.uid
db.collection("games").whereField("userTrackingGame", isEqualTo: currentUid).getDocuments { (querySnapshot, err) in
if let err = err {
print("error getting documents: \(err)")
completion(nil)
return
}
else {
for document
in querySnapshot!.documents {
print(document)
counter += 1
print("the counter is: \(counter)")
}
completion(counter)
}
}
}
How to use
runQueryForNumberOfGames {[weak self] (counter) in
if let count = counter {
print(count)
}
}
推荐阅读
- mule - 具有相同属性名称的 xml 元素被覆盖
- javascript - 外部 fetch 函数中的 this.props 未定义
- java - 我无法使用 JDBC 驱动程序在 Java 中使用 SOAP Web 服务在 MYSQL 中进行插入
- python - 在 Python 中添加时间值
- php - SendGrid 在 Wordpress 函数中使用 api v3 和 PHP 库发送给多个收件人
- java - Java - 使用 Mockito 测试模拟
- javascript - 在 Adobe Animate cc 中使用随机数设置间隔
- r - 使用 TeX() 在 R 中的轴文本中的粗体文本
- php - php和mysql从一种形式插入多个表
- reactjs - 反应原生材质图标 css 样式