Ios 在Swift中存储异步云Firestore查询结果
我正在使用Swift 5、SwiftUI和Firebase进行一个简单的项目,它在数组中循环给定的id,在Cloud Firestore数据库中搜索每个id,并将与id关联的相应名称附加到一个新数组中 以下是我的数据库的图片: 例如,给我一个数组几个id,然后对于给定数组中的每个元素,我获取与该id关联的文档,然后打印该文档中的firstname字段 但是,我希望将检索到的每个firstname值存储到本地单独的数组中,以供以后使用。在Javascript中,我知道这是使用await和async函数完成的,但通过无数小时的故障排除,我发现Swift没有async或await 这是我的密码:Ios 在Swift中存储异步云Firestore查询结果,ios,swift,firebase,asynchronous,google-cloud-firestore,Ios,Swift,Firebase,Asynchronous,Google Cloud Firestore,我正在使用Swift 5、SwiftUI和Firebase进行一个简单的项目,它在数组中循环给定的id,在Cloud Firestore数据库中搜索每个id,并将与id关联的相应名称附加到一个新数组中 以下是我的数据库的图片: 例如,给我一个数组几个id,然后对于给定数组中的每个元素,我获取与该id关联的文档,然后打印该文档中的firstname字段 但是,我希望将检索到的每个firstname值存储到本地单独的数组中,以供以后使用。在Javascript中,我知道这是使用await和asyn
func convertToNames(arr: [String]) -> [String]{
var newArr : [String] = []
for id in arr {
let docRef = db.collection("users").document(id)
docRef.getDocument { (document, error) in
if let document = document, document.exists {
let dataDescription = document.data().map(String.init(describing:)) ?? "nil"
let data = document.get("firstname") ?? "nil"
print("gotten data: \(data)")
newArr.append(String(describing: data))
} else {
print("Document does not exist")
}
}
}
print("NEW ARRAY: \(newArr)")
return (newArr)
}
这段代码完成后会打印一个空数组,我理解为什么,但我不知道如何在Swift中工作。今天我花了大约5个小时浏览Firebase文档,查看示例代码,并浏览Youtube,但没有一个资源能够满足我的需要。如果无法完成,请告诉我。除了完成任务外,您还需要一个调度组
func convertToNames(arr: [String],completion:@escaping(([String]) -> ())) {
var newArr : [String] = []
let g = DispatchGroup()
for id in arr {
let docRef = db.collection("users").document(id)
g.enter()
docRef.getDocument { (document, error) in
if let document = document, document.exists {
let dataDescription = document.data().map(String.init(describing:)) ?? "nil"
let data = document.get("firstname") ?? "nil"
print("gotten data: \(data)")
newArr.append(String(describing: data))
g.leave()
} else {
print("Document does not exist")
g.leave()
}
}
}
g.notify(queue:.main) {
print("NEW ARRAY: \(newArr)")
completion(newArr)
}
}
召唤
getDocument是异步的,会立即返回。数据在回调中可用,一段时间后。您需要为swift采用异步编程技术,这意味着您的函数将不能只返回字符串。
convertToNames(arr:<#arr#>) { res in
print(res)
}