I am trying to access my firestore database which store the userid, username in the collection called user, I want to return the username of the current user, however when I try to run the below function, it is returning me nil value.... do you know anything that I'm missing? A completion handler?
func display(userid: String) -> String
{
var displayname: String
let docRef = db.collection("user").document(uid)
docRef.getDocument { (document, error) in
if let document = document, document.exists {
displayname = document.get("username") as! String
} else {
print("Document does not exist")
}
}
return displayname
}
Then I tried to change to this but it still doesn't change my variable. It seems like it's trapped inside my function
var name = "placeholder"
func display(userid: String, completion: @escaping (String) -> Void) {
let docRef = db.collection("user").document(userid)
docRef.getDocument { (document, error) in
if let document = document, document.exists {
if let displayName = document.get("username") as? String {
self.name = displayName
completion(displayName)
}
} else {
print("Document does not exist")
}
}
}
func create()
{
display(userid: uid){
[weak self] displayName in
print(displayName)
self!.name = displayName
}
var ref: DocumentReference? = nil
ref = db.collection("Request").addDocument(data: ["requestername": "name"]
.....
}