让AuthListener等待for循环完成

时间:2019-05-18 13:44:07

标签: ios swift firebase firebase-realtime-database

我每次登录时都会读取用户的数据。由于我在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循环完成?

1 个答案:

答案 0 :(得分:0)

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

在代码中看起来像这样:

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)
}