I am making an iOS app in Swift with user data stored in a Firebase Firestore database. The user documents in Firestore are named by the UID's of the users. To get the data from Firestore, I have the function getUserData:
static func getUserData(uid: String) -> [String : Any] {
let userRef = Firestore.firestore().collection(Constants.Firestore.Collections.users)
let userDocRef = userRef.document(uid)
var temp: [String : Any] = [:]
userDocRef.getDocument { (document, error) in
guard let document = document, document.exists else {
print("document does not exist")
return
}
let dataDesc = document.data()
temp = dataDesc!
}
return temp
}
I call this method in an initializer for my user class:
class User {
// MARK: - Properties
var firstName: String
var lastName: String
let uid: String
let phone: String
var available: Bool
var friends: [User] = []
init?(firestoreUID: String) {
self.uid = firestoreUID
let data = UserService.getUserData(uid: firestoreUID)
print(data.keys)
guard let phone = data[Constants.Firestore.Keys.phone] as? String,
let available = data[Constants.Firestore.Keys.available] as? Bool,
let firstName = data[Constants.Firestore.Keys.firstName] as? String,
let lastName = data[Constants.Firestore.Keys.lastName] as? String
else {
return nil
}
self.phone = phone
self.available = available
self.firstName = firstName
self.lastName = lastName
}
}
However, when I unwrap the user instance, it gives a nil value. When I printed the keys of the retrieved dictionary from the getUserData function, the console shows only an empty array. What am I doing wrong, and how can I fix this so that I actually get my users' data from Firestore?
Edit: I've changed getUserData to boss's answer, but I'm not sure what should be in my User class init. I tried the call format suggested with ``` UserService.getUserData(uid: firestoreUID) { (data) in
if let data = data {
print(data.keys)
temp = data
} else {
print("User not found")
return
}
}
But I still get a "Fatal error: Unexpectedly found nil when unwrapping an optional value" when I try to query the temp dictionary.