Reputation: 737
I am retrieving a snapshot of all of the users in my Firebase database. After I append all of my users from my "users" node of my database to an array of users , I attempt to print the user count (which should be 12) and it says it is 0 instead.
I added a breakpoint at the closing brace of the if-statement which shows to me that the user count reaches 12. However, by the time it comes time to print this number, it is zero. Stepping through a bunch of times is just a lot of assembly code that tells me nothing.
I call this function in the viewDidLoad() method and tried to print the users count after this function is called in addition to printing it within the function and it is still 0.
func getUsers() {
let ref = Database.database().reference().child("users")
ref.observe(.childAdded, with: { (snapshot) in
if let dictionary = snapshot.value as? [String: AnyObject] {
let user = User()
user.id = snapshot.key
user.setValuesForKeys(dictionary)
self.users.append(user)
}
}, withCancel: nil)
print(users.count)
}
Upvotes: 1
Views: 313
Reputation: 13043
Here you go, a fix below. Like Ahmed is saying: it takes some time to get the data since it is async.
func getUsers(completionHandler:@escaping (Int) -> ()){
let ref = Database.database().reference().child("users")
ref.observe(.childAdded, with: { (snapshot) in
if let dictionary = snapshot.value as? [String: AnyObject] {
let user = User()
user.id = snapshot.key
user.setValuesForKeys(dictionary)
self.users.append(user)
completionHandler(self.users.count)
}
})
override func viewDidLoad() {
super.viewDidLoad()
getUsers(){ (count) in
print(count)
}
}
It is pretty straightforward what is going on, I just added a completion handler.
Upvotes: 3
Reputation: 240
Because observe work asynchronously, and you are printing users.count before updating users array...
Upvotes: 2