Search code examples
swiftfirebasegoogle-cloud-firestoreuilabel

How to fetch user data from cloud firestore


Could someone help me with retrieving the "firstname" data off my collection in firebase. I want to display the user name on the user profile to a UILable called "nameLable", but I'm not sure how?

I want each user to be able to see their name on the profile page if anyone can help! I'm using cloud firestore.

Firebase collection


Solution

  • You can use the following piece of code to get the first name of every user in the document list.

    func getName(Completion: @escaping((String) -> ())) {
        let collectionRefernce:CollectionReference!
        let db = Firestore.firestore()
        collectionRefernce = db.collection("members")
        collectionRefernce.getDocuments { (querySnapshot, error) in
            if error != nil {
                print("Error is \(error!.localizedDescription)")
            } else {
                guard let snapshot = querySnapshot else { return }
                for document in snapshot.documents {
                    guard let myData = document.data() else { return }
                    let firstname = myData["firstName"] as? String ?? "No Name Found"
                    Completion(firstname)
                }
            }
        }
    }
    

    This will retrieve firstname of every user. To call the function:

    getName{ (name) in
        label.text = name
      }
    

    In case you want to retrieve the firstName of the currently logged in user, use the code below

    let id = Auth.auth().currentUser!.uid
     func getName(Completion: @escaping((String) -> ())) {
        let DocRefernce:DocumentReference!
        let db = Firestore.firestore()
        DocRefernce = db.collection("members").document(id)
        DocRefernce.getDocument { (docSnapshot, error) in
            if error != nil {
                print(error!)
            } else {
                guard let snapshot = docSnapshot, snapshot.exists else { return }
                guard let data = snapshot.data() else { return }
                let firstname = data["firstName"] as? String ?? "No name"
                Completion(firstname)
            }
        }
    
    }
    

    Then call it in viewDidLoad like this

    getName{ (name) in
      label.text = name
     }