我需要在ProfileView中的文本上显示用户名,但是当我尝试用用户填充当前用户时出错。我必须在currentUser变量中获取用户。
import Foundation
import FirebaseAuth
import Firebase
class AuthViewModel: ObservableObject
{
@Published var userSession: FirebaseAuth.User?
@Published var currentUser: User?
private var tempUserSession: FirebaseAuth.User?
private let service = UserService()
init()
{
self.userSession = Auth.auth().currentUser
}
func login(withEmail email: String, password: String)
{
Auth.auth().signIn(withEmail: email, password: password) { authResult, error in
if let e = error
{
print(e.localizedDescription)
}
else
{
guard let user = authResult?.user else {return}
self.userSession = user
guard let uid = self.userSession?.uid else { return }
self.service.fetchUser(withUid: uid)
print("Did User log IN")
}
}
}
func fetchUser()
{
guard let uid = self.userSession?.uid else { return }
service.fetchUser(withUid: uid) { user in <----- HERE I GOT AN ERROR Extra trailing closure passed in call
self.currentUser = user
}
}
}
import Foundation
import UIKit
import FirebaseAuth
import SwiftUI
class ProfileViewController: UIViewController
{
var authViewModel = AuthViewModel()
@IBOutlet weak var userNameLabel: UILabel!
override func viewDidLoad()
{
navigationItem.hidesBackButton = true
userNameLabel.text = authViewModel.currentUser?.username // HERE I WANT TO DISPLAY CURRENT USER - USERNAME
print(userNameLabel.text)
}
}
我试着用user填充currentuser,但是没有效果。仍然在profile视图控制器中,我得到了nill。(currentUser. username = nil)
1条答案
按热度按时间pgvzfuti1#
这段代码调用
fetchUser
就像它是一个异步函数一样,但它不是;它是一个同步函数,不返回值,也没有转义完成处理程序,所以这就是错误的原因。我将这样做:从一个简单的用户类开始
然后使用async/await简化
fetchUser
然后是从Firestore获取用户、示例化MyUser对象并返回该对象的代码