首页 > 解决方案 > 将数据从 Firestore 存储到列表

问题描述

我有一个数据库,存储用户每天输入的一系列整数值并存储为整数列表。我有以下代码查询数据库并将搜索到的症状值存储到一个列表中,然后从函数中返回,而通过 for 循环返回的数据似乎包含数据库中的所有值但是当我print(returnedData)只放置在查询之后和 return 语句之前,它会打印一个空列表。我不太确定为什么 for 循环没有正确附加到返回的数据列表中。

func yearDataReturn(year: Int,symptom: String)->[Int]{
    //fetches all the year for the month and returns it as a list
    let collectionRef = db.collection("entries")
    var returnedData:[Int] = []
    collectionRef.whereField("year", isEqualTo: year).whereField("UserID", isEqualTo: UserDefaults.standard.integer(forKey: "UserID")).order(by: "monthOfYear").order(by: "weekOfMonth").order(by: "dayOfMonth")
        .getDocuments{(QuerySnapshot,err)in
            for doc in QuerySnapshot!.documents{
                let sympLis=doc.get("SymptomValues") as! [Int]

                let symp=sympLis[self.symptoms.firstIndex(of: symptom)!]
                returnedData.append(symp)
            }

    }
    return returnedData

}

标签: swiftfirebasegoogle-cloud-firestore

解决方案


首先欢迎来到本站。


这是一个异步调用,这意味着查询行的 ( collectionRef.whereField(...) 块将在该return returnedData行之后执行。

请查看这篇中型文章 ->在 Swift 中管理异步代码


您可以closure像这样将 a 传递给您的函数->

func yearDataReturn(year: Int,symptom: String, completion: @escaping ([Int] -> Void)) {
  //fetches all the year for the month and returns it as a list
  let collectionRef = db.collection("entries")
  var returnedData:[Int] = []

  collectionRef.whereField("year", isEqualTo: year).whereField("UserID", isEqualTo: UserDefaults.standard.integer(forKey: "UserID")).order(by: "monthOfYear").order(by: "weekOfMonth").order(by: "dayOfMonth")
    .getDocuments{(QuerySnapshot,err)in
      for doc in QuerySnapshot!.documents{
        let sympLis=doc.get("SymptomValues") as! [Int]

        let symp=sympLis[self.symptoms.firstIndex(of: symptom)!]
        returnedData.append(symp)
      }
      completion(returnedData)
  }
}

用法


yearDataReturn(year: 5, symptom: "asdf") { symptomValues in
  print(symptomValues)
}


推荐阅读