I'm pretty new to SwiftUI and using Firebase and have stumbled upon retrieving a value from a document on Firebase. I've done some Googling but have yet to find a way to do this.
My code so far looks like this:
//Test1: get user info
func readUserInfo(_ uid: String) -> String {
let db = Firestore.firestore()
let docRef = db.collection("users").document(uid)
var returnThis = ""
docRef.getDocument { (document, error) -> String in
if let document = document, document.exists {
let dataDescription = document.data().map(String.init(describing:)) ?? "nil"
print("Document data: \(dataDescription)")
returnThis = dataDescription
return(dataDescription)
} else {
print("Document does not exist")
}
}
return returnThis
}
//Test2: get user info
func readUserInfo(_ uid: String) -> String {
let db = Firestore.firestore()
let docRef = db.collection("users").document(uid)
var property = "not found"
docRef.getDocument { (document, error) in
if let document = document, document.exists {
property = document.get("phoneNumber") as! String
}
}
return property
}
Test1: Got an error saying "Declared closure result 'String' is incompatible with contextual type 'Void'"
Test2: The returned value is always "not found", so I guess assigning document.get("phoneNumber") as! String to the property variable didn't work.
In both cases, I was able to print the value out. However, I want the value to be passed to a Text element so I can display it on the interface.
Could someone please help? Thanks so much in advance.