我在每次登录时都会读取用户的数据。由于我在AppDelegate.swift内部有一个Firebase AuthListener,因此一旦用户登录,视图就会更改。

问题是,在某些情况下,视图的更改速度快于处理数据的速度,导致进入没有所需数据的屏幕。

过去,我通过在代码中添加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循环完成?

最佳答案

您想要等待进入新视图,直到所有数据都已加载。一种方法是计算已经加载了多少个子节点,然后在加载所有子节点后继续。

在代码中看起来像这样:

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/

10-13 03:15