swift - 错误的元素出现在 Firebase querySnapshot 中

标签 swift firebase google-cloud-firestore

我在 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/

相关文章:

firebase - 在 flutter 中映射 Firebase 流

node.js - 无法使用对话流实现将数据添加到 firestore

ios - 无法获取非方形图像的字节

xcode - 如何获取 Watchkit Extension 中所有图像文件的列表

java - 根据已知的 uid 从 firebase 检索用户名

javascript - Firebase 存储安全规则拒绝读取权限,即使 "allow read: if true"

go - 如何使用Go将文档ID插入为字段值Firestore

ios - 如何在不重复使用的情况下选择 TableView 中的第一个单元格?

ios - 自定义分段控件不切换 View

ios - 当前用户重新登录后 Firebase 无法正常工作