gpt4 book ai didi

ios - 让 AuthListener 等待,直到 for 循环完成

转载 作者:行者123 更新时间:2023-11-29 05:45:22 24 4
gpt4 key购买 nike

我在每次登录时都会读取用户的数据。由于我在 AppDelegate.swift 中有一个 Firebase AuthListener,因此一旦用户登录, View 就会发生变化。

问题是,在某些情况下, View 的变化速度快于数据的处理速度,这会导致屏幕上没有所需的数据。

过去,我通过在更改 View 的代码中添加: databaseRef.observeSingleEvent(of: .value, with: { snap in ... }) 来绕过此问题:

if user != nil && currentCar == "auto auswählen" {
databaseRef.observeSingleEvent(of: .value, with: { snap in
if user?.isAnonymous == false {
let controller = storyboard.instantiateViewController(withIdentifier: "RootPageViewController") as! RootPageViewController
let vc = storyboard.instantiateViewController(withIdentifier: "ProfileViewController") as! ProfileViewController
vc.readTimeline()
self.window?.rootViewController = controller
self.window?.makeKeyAndVisible()
} else if user?.isAnonymous == true {
let controller = storyboard.instantiateViewController(withIdentifier: "RootPageViewController") as! RootPageViewController
self.window?.rootViewController = controller
self.window?.makeKeyAndVisible()
}
})

这工作得很好,但现在我在 for 循环的帮助下读取数据,它不会,因为数据库请求比 for 循环更早完成:

databaseRef.child("users").child(uid).observeSingleEvent(of: .value, with: { (snapshot) in
let value = snapshot.value as? NSDictionary

for n in 1...snapshot.childrenCount {
databaseRef.child("users/\(uid)").child(String(n)).observeSingleEvent(of: .value, with: { (snapshot) in
let value = snapshot.value as? NSDictionary

...

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

如何让 AppDelegate.swift 和 AuthListener 等待 for 循环完成?

最佳答案

您想要等待进入新 View ,直到所有数据加载完毕。一种方法是计算已加载的子节点数量,然后在加载完所有子节点后继续。

代码看起来像这样:

databaseRef.child("users").child(uid).observeSingleEvent(of: .value, with: { (snapshot) in
let value = snapshot.value as? NSDictionary
let loadedCount = 0

for n in 1...snapshot.childrenCount {
databaseRef.child("users/\(uid)").child(String(n)).observeSingleEvent(of: .value, with: { (snapshot) in
loadedCount = loadedCount + 1
let value = snapshot.value as? NSDictionary

...

if (loadedCount == snapshot.childrenCount) {
// TODO: all data is loaded, move to the next view
}
}) { (error) in
print(error.localizedDescription)
}
}
}) { (error) in
print(error.localizedDescription)
}

关于ios - 让 AuthListener 等待,直到 for 循环完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56199524/

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