[英]SwiftUI FireStore - Get Field from Document and display as Text()
I'm very new to SwiftUI so bare with me - it's for a project.我对 SwiftUI 很陌生,所以对我来说很简单 - 这是一个项目。
I have stored user's details into my Firestore database which looks like this:我已将用户的详细信息存储到我的 Firestore 数据库中,如下所示:
I want to take the name from the database and display it in a Text("Hello" [name]) I have been able to fetch the name from the database and append it into an array.我想从数据库中获取名称并将其显示在 Text("Hello" [name]) 我已经能够从数据库中获取名称并将 append 提取到数组中。 This function is run when the 'Log in' button is clicked.单击“登录”按钮时,将运行此 function。
The code is as follows:代码如下:
func getData(){
let docRef = db.collection(FStore.collectionName).document(userID)
docRef.getDocument { (document, error) in
if let document = document, document.exists {
if let fetchedName = document.get("name") as? String {
userArray.append(fetchedName)
print(userArray)
}
}
}
} }
When printing userArray, the correct name does print.打印 userArray 时,会打印正确的名称。 However I am struggling to display the name outside of the console and on my Text UI field.但是,我正在努力在控制台之外和我的 Text UI 字段上显示名称。 When I attempt the code below, it gives me an index out of range error.当我尝试下面的代码时,它给了我一个索引超出范围的错误。
Text("Hello: \(userArray[0])")
Any help is appreciated / any other methods of retrieving field data from a specific document.任何帮助表示赞赏/从特定文档中检索字段数据的任何其他方法。
Thanks to @Steve M , it ended up being a kind of silly mistake.感谢@Steve M ,它最终成为一种愚蠢的错误。
He was right, the display was attempting to read the array before the array had even been populated.他是对的,显示器甚至在阵列被填充之前就试图读取阵列。
As described in my comments, I called the getData() function then ran code to display the next screen.如我的评论中所述,我调用 getData() function 然后运行代码以显示下一个屏幕。 I wrapped the "display next screen code" in a DispatchQueue to delay the next screen being displayed我将“显示下一个屏幕代码”包装在 DispatchQueue 中以延迟显示下一个屏幕
DispatchQueue.main.asyncAfter(deadline@ .now() + 1){
nextView = true
}
This ran a 1-second delay before displaying the next screen and successfully displayed the name from the database.在显示下一个屏幕并成功显示数据库中的名称之前,这会延迟 1 秒。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.