Firebase登录用户在segue之前没有足够快地加载

时间:2017-03-15 21:17:06

标签: ios swift firebase firebase-realtime-database

我正按下此按钮

override func viewDidLoad() {
    FIRAuth.auth()?.signIn(withEmail: "hakuna.matata.kitty@gmail.com", password: "password") {
        (user, error) in
        // TODO: SET UP A SPINNER ICON
        print("Logged into hmk")
        self.performSegue(withIdentifier: "login", sender: self)
    }
}

如您所见,在回调时,它会重定向到UITableViewController。 populator代码位于UITableViewController的初始化器中,闭包的唯一目的是填充self.chatsList

有时,每当我测试应用程序时,UITableViewController都是空白的。

ref.child("users").child(currentUser.uid).observeSingleEvent(of: .value, with: { (snapshot) in
    guard snapshot.exists() else {
        print("Error: Path not found")
        return
    }

    let value = snapshot.value as? NSDictionary
    // Convert a dict of dicts into an array of dicts
    // You will lose chatID in the process, so be warned
    // Unless you would like to to keep the data in a struct
    for (chatIdKey, secondDict) in value?["chats"] as! [String: NSDictionary] {
        // This only appends metadata for the last chat
        // Does not load every chat message
        self.chatsList.append(Chat(chatId: chatIdKey, targetChat: secondDict))
    }
})

但是当我按下后退键,等待足够长时间,再次登录时,表格就会正确填充。

如何确保每次都正确加载?我预计回调的performSegue会保证我们确实有一个currentUser ...

1 个答案:

答案 0 :(得分:1)

我认为你的观察者应该改变。我看到这个tableview将是某种聊天,所以你可能希望在用户进入ViewController时保持引用处于活动状态,这样你可以只使用observeSingleEvent而不是observe并手动删除观察者离开视野。

另一件事是你正在观察值,当你应该观察childAdded时,好像在用户不会收到它的“聊天”视图中添加了任何事件。

更改以下行,看看这是否适合您。

ref.child("users").child(currentUser.uid).observe(.childAdded, with: { (snapshot) in

希望它有所帮助!