[英]Array is null after trying to fetch data in swift app
I am trying to save an array which I have stored in firestore in a local array我正在尝试将存储在 firestore 中的数组保存在本地数组中
this is the method where the error occurs:这是发生错误的方法:
func getEvents() async {
let db = Firestore.firestore()
var allEvents = [String]()
var docIDuser = ""
docIDuser = UserDefaults.standard.object(forKey: "userDocID") as! String
try? await db.collection("user").document(docIDuser).getDocument() { (document, error) in
if let document = document, document.exists {
allEvents = (document.data()!["events"] as? [String])!
} else {
print("Document does not exist")
}
}
for element in allEvents {
try? await db.collection("event").document(element as! String).getDocument() { (document, error) in
if let document = document, document.exists {
let ev = document.data()!
self.eventlist.append(Event(id: document.documentID, name: document["eventname"] as? String ?? ""))
} else {
print("Document does not exist")
}
}
}
}
I tried to debug the code and within this part:我尝试调试代码,并在这一部分中:
try? await db.collection("user").document(docIDuser).getDocument() { (document, error) in
if let document = document, document.exists {
allEvents = (document.data()!["events"] as? [String])!
} else {
print("Document does not exist")
}
}
allEvents is filled with the values that I need but as soon as I leave the block, allEvents doesn't have any values left. allEvents 填充了我需要的值,但是一旦我离开块, allEvents 就没有任何值了。 It is probably an async problem but I don't get why it isn't working since I am trying to avoid this issue by implementing async/await
这可能是一个异步问题,但我不明白为什么它不起作用,因为我试图通过实现 async/await 来避免这个问题
this is where I call the method:这是我调用该方法的地方:
Button(action: {
Task {
try? await viewModel.getEvents()
}
}, label: {
Text("events test")
})
any help would be appreciated任何帮助,将不胜感激
You are not supposed to use a closure when using async/await with firebase.将 async/await 与 firebase 一起使用时,您不应该使用闭包。
Instead of the closure the function will return the values. function 将返回值,而不是关闭。
let result = try? await db.collection("user").document(docIDuser).getDocument()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.