I’ve been following the tutorials. I created a User structure and a UserModel class. I have a view controller which calls a method from the UserModel class. That class is supposed to return a User structure with various details about that user. However, the method is “unexpectedly returning nil.” I have tested the method inside my view controller class and it works there. However, it doesn’t work within its own class. (Note: the User Id is printing, and the method works within class: each value from the database was found and applied to the User struct and able to be printed out.)
My UserModel class:
class UserModel {
var user:User?
func getUser(userId: String) -> User? {
let docRef = Firestore.firestore().collection("Users").document(userId)
// Get data
docRef.getDocument { (document, error) in
if let document = document, document.exists
{
var user:User = User(name: document["name"] as! String, phone: document["phone"] as! String, imageUrl: document["imageUrl"] as! String)
} else
{
print("Document does not exist")
}
}
return user!
}
My User struct file:
struct User {
var name:String
var phone:String
var imageUrl:String
}
My View controller:
override func viewDidLoad() {
super.viewDidLoad()
userId = Auth.auth().currentUser?.uid
}
override func viewDidAppear(_ animated: Bool) {
let model = UserModel()
user = model.getUser(userId: userId!)
print(user?.name)
}
Any ideas?