swift 如何在ProfileViewController中显示用户对象的名称

pw9qyyiw  于 2023-01-04  发布在  Swift
关注(0)|答案(1)|浏览(110)

我需要在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)

pgvzfuti

pgvzfuti1#

这段代码调用fetchUser就像它是一个异步函数一样,但它不是;它是一个同步函数,不返回值,也没有转义完成处理程序,所以这就是错误的原因。
我将这样做:从一个简单的用户类开始

class MyUser {
    var userName = ""
    var uid = ""
}

然后使用async/await简化fetchUser

func fetchUser() {
    Task {
        let uid = "uid_0"
        let foundUser = await self.getUserAsync(withUid: "uid_0")

        print(foundUser.userName)
    }
}

然后是从Firestore获取用户、示例化MyUser对象并返回该对象的代码

func getUserAsync(withUid: String) async -> MyUser {
    let usersCollection = self.db.collection("users") //self.db points to my firestore
    let thisUserDoc = usersCollection.document(withUid)
    let snapshot = try! await thisUserDoc.getDocument()

    let user = MyUser()
    user.userName = snapshot.get("userName") as? String ?? "No Name"
    user.uid = withUid

    return user
}

相关问题