【发布时间】:2021-12-26 00:53:59
【问题描述】:
我有一个类,它有一个函数可以获取用户名以在视图上打印它。 它可以工作,但是我延迟了将近一秒钟,因为没有看到用户名。
这里是类:
class ViewModel: ObservableObject {
@Published var username: String = ""
func benutzerdaten_accountview (email: String) -> String {
let db = Firestore.firestore()
let docRef = db.collection("Nutzer").document(email)
docRef.getDocument{ (document, error) in
if let document = document, document.exists{
self.username = (document.data()!["username"] as? String)!
}
}
return username
}
}
这就是我在视图上打印它的方式:
struct AccountView: View{
@ObservedObject var model = ViewModel()
@Binding var tabSelection: Int
var email: String = (Auth.auth().currentUser?.email)!
var body: some View {
VStack{
Text("Hallo, \(model.benutzerdaten_accountview(email: email).description)")
...
【问题讨论】:
-
如果实际返回了正确的
username,我会感到惊讶。从外观上看,我认为它不会从原来的空字符串改变,直到之后。所以返回对于异步闭包中设置的值是没有意义的。 -
我该如何解决?
-
我们不在 SwiftUI 中使用视图模型
标签: swift firebase google-cloud-firestore swiftui