gpt4 book ai didi

swift - 为什么我的 swift 代码执行无序? Firebase 身份验证

转载 作者:行者123 更新时间:2023-12-02 02:33:20 26 4
gpt4 key购买 nike

我正在调用 Authenticator.loginUser(),期望该方法将登录用户,然后调用 getCurrentUser()。根据打印输出,getCurrentUser() 首先执行。有没有办法强制它按顺序执行?

class Authenticator: ObservableObject {

@Published var currentUser: UserProfile = UserProfile()
@Published var user: String = ""
@Published var documentId: String = ""

func loginUser (email: String, password: String, viewModel: UsersViewModel) {
FirebaseAuth.Auth.auth().signIn(withEmail: email, password: password, completion: { result, error in

guard error == nil else {
print ("error: \(error!)")
return
}
print ("user signed in")
})
self.user = self.getCurrentUser(viewModel: viewModel)
}

func getCurrentUser(viewModel: UsersViewModel) -> String {
guard let userID = Auth.auth().currentUser?.uid else {
return ""
}

viewModel.users.forEach { i in
if (i.userId == userID) {
currentUser = i
}
}

documentId = currentUser.documentId!
print("auth.documentId \(documentId)")
return userID
}

}

最佳答案

FirebaseAuth.Auth.auth().signIn异步 - 它在后台运行,线程上。这意味着 signIn 将在将来的某个时间被调用。

解决方案是将 getCurrentUser 的调用放在完成 block 中:

func loginUser(email: String, password: String, viewModel: UsersViewModel) {
FirebaseAuth.Auth.auth().signIn(withEmail: email, password: password, completion: { result, error in
guard error == nil else {
print("error: \(error!)")
return
}
print("user signed in")
self.user = self.getCurrentUser(viewModel: viewModel) // move here
})
}

关于swift - 为什么我的 swift 代码执行无序? Firebase 身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64722904/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com