gpt4 book ai didi

ios - Firebase 和 Swift - 延迟更改 ViewController 直到读取数据

转载 作者:搜寻专家 更新时间:2023-11-01 06:52:50 25 4
gpt4 key购买 nike

我实现了一个登录,每次用户登录时从实时数据库加载数据。当用户成功登录时,正在读取数据 - 问题是 AppDelegate更改 ViewController 的速度比读取数据的速度快。因此,在应用程序再次关闭之前不会显示任何内容。

有没有办法延迟 View 的更改,直到读取数据?

didFinishLaunchingOptions()AppDelegate 中:

let authListener = Auth.auth().addStateDidChangeListener { auth, user in

let storyboard = UIStoryboard(name: "Main", bundle: nil)

if user != nil {
let controller = storyboard.instantiateViewController(withIdentifier: "RootPageViewController") as! RootPageViewController
self.window?.rootViewController = controller
self.window?.makeKeyAndVisible()
} else {
let vc = storyboard.instantiateViewController(withIdentifier: "SettingsTableViewController") as! SettingsTableViewController
vc.runResetData()

let controller = storyboard.instantiateViewController(withIdentifier: "ProfileViewController") as! ProfileViewController
self.window?.rootViewController = controller
self.window?.makeKeyAndVisible()
}
}

登录 View Controller :

@IBAction func login(_ sender: Any) {
guard let email = emailInput.text else { return }
guard let password = passwordInput.text else { return }

Auth.auth().signIn(withEmail: email, password: password) { user, error in
if error == nil && user != nil {
self.readData()
self.dismiss(animated: false, completion: nil)
} else {
print("Error logging in: ", error!.localizedDescription)

let alert = UIAlertController(title: "Fehler beim Einloggen", message: error!.localizedDescription, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Verstanden", style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
}

func readData() {
guard let uid = Auth.auth().currentUser?.uid else { return }
let databaseRef = Database.database().reference()

databaseRef.child("users").child(uid).observeSingleEvent(of: .value, with: { (snapshot) in

let value = snapshot.value as? NSDictionary
let monthlyStartKmData = value?["monthlyStartKm"] as? Int ?? 0
let currentKmData = value?["currentKm"] as? Int ?? 0
...


startKm = monthlyStartKmData
currentKm = currentKmData
...


}) { (error) in
print(error.localizedDescription)
}

}

最佳答案

不,你不能,因为对 listen 的调用是异步的,所以它在设置 rootVC 时延迟运行,你需要显示一个加载器,比如

 let vc = UIViewController()
vc.view.backgroundColor = .red
self.window?.rootViewController = vc
self.window?.makeKeyAndVisible()
let authListener = Auth.auth().addStateDidChangeListener { auth, user in
.....
}

AppDelegate 内部

if FIRAuth.auth().currentUser != nil {
// go to home , if you went before you should have km month values cached
}
else {
// go to login
}

关于ios - Firebase 和 Swift - 延迟更改 ViewController 直到读取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55975415/

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