I'm trying to retrieve data from an Asynchronous function of Firebase and then set it as the ViewController's user variable:
var user : User!
override func viewDidLoad() {
super.viewDidLoad()
collectionView.dataSource = self
fetchUser()
}
func fetchUser(){
Api.User.observeCurrentUser { (user) in
self.user = user
}
The problem is that within the brackets of the 'observeCurrentUser' method I can actually see the user retrieved correctly but outside them the it is not associated to the self.user and when I try to print it outside the brackets it's nil.
Being said this, I searched on the web and I found out that this is because it's an asynchronous function. How can I get the self.user equal to the user retrieved in the 'observeCurrentUser' function so that I can work on it in the ViewController?
The Api.User.observeCurrentUser function retrieves the currentUser. It's coded in this way:
func observeCurrentUser(completion: @escaping (User)-> Void){
guard let currentUser = Auth.auth().currentUser else {
return
}
REF_USERS.child(currentUser.uid).observeSingleEvent(of: .value) { (snapshot) in
if let dict = snapshot.value as? [String: Any]{
let user = User.transformUser(dict: dict)
completion(user)
}
}
}
Where REF_USERS it's the reference of all users in the Firebase-Database
Api.User.? You can access the currently authenticated user anywhere in your app with this codelet user = Auth.auth().currentUser- can you clarify what you're asking? Also, please review the following two guides on asking questions: How do I ask a good question? and How to create a Minimal, Complete, and Verifiable examplefetchUseror – more cumbersome – add a completion handler.