我在 Swift 中开发了一个应用程序,我得到了一个包含数字的数组,我想在 Firebase 中获取一些数据。
问题是 getDocuments
扰乱了我的迭代。
当我用打印输出进行测试时,第一个打印出 0,1,2,3 但第二个,getDocuments
中的那个,显示 0,2,1,3
let test = ["20180905212533","20180905220014","20180905212533","20180905220014"]
for recepieID in 0 ... test.count-1{
print (recepieID) //Shows right recepieID = 0,1,2,3
db.collection("Recipes")
.whereField("created", isEqualTo: test[recepieID])
.getDocuments() { (querySnapshot, err) in
print (recepieID)// Do not show right recepieID = 0,2,1,3
}
}
最佳答案
这个操作是异步的,不能保证服务器会串行响应,要么使用串行队列
let q = DispatchQueue(label: "CustomQueue")
let test = ["20180905212533","20180905220014","20180905212533","20180905220014"]
for recepieID in 0 ... test.count-1{
q.async {
print (recepieID) //Shows right recepieID = 0,1,2,3
db.collection("Recipes")
.whereField("created", isEqualTo: test[recepieID])
.getDocuments() { (querySnapshot, err) in
print (recepieID)// Do not show right recepieID = 0,2,1,3
}
}}
或
load(0)
//
func load(_ recepieID:Int) {
db.collection("Recipes")
.whereField("created", isEqualTo: test[recepieID])
.getDocuments() { (querySnapshot, err) in
print (recepieID)// Do not show right recepieID = 0,2,1,3
if recepieID < test.count {
load(recepieID+1)
}
}
}
关于swift - 错误的元素出现在 Firebase querySnapshot 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52293009/