0

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"]

.....
}
                                                
    
Dharman
  • 30,962
  • 25
  • 85
  • 135
Jeff
  • 3
  • 2

1 Answers1

1

You need to use closures as getDocument() does not return synchronously.

func display(userid: String, handler: (String) -> Void) {
    let docRef = db.collection("user").document(uid)
    docRef.getDocument { (document, error) in
        if let document = document, document.exists {
            if let displayName = document.get("username") as? String {
                handler(displayName)
            }
        } else {
            print("Document does not exist")
        }
    }
}

And use it like so:

self.myLabel.text = "Loading..."
display(userid: {USER_ID}) { [weak self] displayName in
    print(displayName)
    self.myLabel.text = displayName
}
Eilon
  • 2,698
  • 3
  • 16
  • 32
  • hi Eilon, thanks for the reply. However, when i call this function i want to return the username which will be displayed in a text label.... but when i tried to display in the textlabel.. it says..cannot assign value () to type String.. do u know why? – Jeff Sep 27 '20 at 02:47
  • You cannot use this as a normal function because the call is asynchronous while functions are synchronous. Check out the updated answer for a more specific example. – Eilon Sep 27 '20 at 08:23
  • thanks so much! i have added @escaping too for my function to work elsewhere! – Jeff Sep 27 '20 at 16:28