Reputation: 333
Ok, so my text label should display the name of the user, but the codes runs before the user data is fetched and the label doesn't change when the data is loaded.
First time i print the users name i get nil, but when i print within the firebase call i get the users name. how can i do this so i don't have to change the label with in the firebase call?
var ref: FIRDatabaseReference!
var user: User!
override func viewDidLoad() {
super.viewDidLoad()
ref = FIRDatabase.database().reference()
fetchUser()
self.titleLabel.text = user?.name
// Returns nil
print(user?.name)
}
func fetchUser() {
ref.child("users").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
let value = snapshot.value as? NSDictionary
let name = value?["name"] as? String ?? ""
let birthdate = value?["birthdate"] as? String ?? ""
let gender = value?["gender"] as? String ?? ""
self.user = User(name: name, birthdate: birthdate, gender: gender)
// Now i get the users name
print(self.user.name)
}) { (error) in
print(error.localizedDescription)
}
}
Upvotes: 2
Views: 1067
Reputation: 5616
If you do not want to access the label from fetchUser
, you can use a simple callback.
override func viewDidLoad() {
//viewDidLoad code
fetchUser() {
self.titleLabel.text = user?.name
}
}
func fetchUser(_ completion: @escaping () -> Void) {
ref.child("users").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
//fetchUser code
// Now i get the users name
print(self.user.name)
completion()
}) { (error) in
print(error.localizedDescription)
}
}
Upvotes: 2