Reputation: 1747
I'm hitting this button
override func viewDidLoad() {
FIRAuth.auth()?.signIn(withEmail: "[email protected]", password: "password") {
(user, error) in
// TODO: SET UP A SPINNER ICON
print("Logged into hmk")
self.performSegue(withIdentifier: "login", sender: self)
}
}
As you can see, on callback it redirects to a UITableViewController. The populator code sits in the initializer of UITableViewController, the sole purpose in the closure is to populate self.chatsList
Sometimes, whenever I test out the app, the UITableViewController is blank.
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))
}
})
But when I hit the back key, wait long enough, and login again, the table is populated properly.
How can I make sure that it loads correctly every time? I expected the performSegue on callback would guarantee that we do have a currentUser...
Upvotes: 1
Views: 102
Reputation: 9356
I think your observer should be changed. I see this tableview will be some kind of chat so you might want to keep the reference alive while the user is in that ViewController so instead of using observeSingleEvent
you could just observe
and you manually remove the observer when leaving the view.
Another thing is that you are observing the value when you should probably observe the childAdded as if any event is added while being in the "chat" view the user will not receive it.
Change the line below and see if this works for you.
ref.child("users").child(currentUser.uid).observe(.childAdded, with: { (snapshot) in
Hope it helps!
Upvotes: 1