iosswift4

Firesbase authentication iOS login get user detail


I have just followed and correctly added the following tutorial to my app. But I’m struggling on how to get the ‘logged in’ users details from the Firestore database?

The Tutorial:

https://youtu.be/1HN7usMROt8

Once the user registers through my app the ‘First name’, ‘last name’ and ‘UID’ are saved by the Firestore database. But once the user logs in how do I GET the users first name to copy to a label on a welcome screen inside the app?

Thanks


Solution

  • I suppose that you know how Firestore works. If you don't you can get all information in this documentation or watch videos about Firestore on YouTube.

    So let's say you have your users saved in collection named users. When the user sign in you can get current user like this:

    let currentSignInUser = Auth.auth().currentUser!
    

    If you will force unwrap it make sure that user will be signed in.

    When you have current user you can get his UID by calling uid property of current user:

    let currentUserID = currentSignInUser.uid
    

    Now you can query this UID to get documents from Firestore users collection that have same UID field value as your current signed in user:

    let query = Firestore.firestore().collection("users").whereField("UID", isEqualTo: currentUserID)
    

    Make sure that the first parameter of whereField() function is same as your field name in documents. Because you mentioned that UID is saved to database I named it UID.

    This is all for getting information of your current user and making query out of it. Now you can GET documents from Firestore:

    query.getDocuments() { [weak self] (querySnapshot, err) in
            if let err = err {
                print("Error getting documents: \(err)")
            } else {
                if let userInfo = querySnapshot?.documents.first { 
                    DispatchQueue.main.async {
                        // Set label text to first name
                        self?.youLabel.text = userInfo["firstName"]
                    }
                }
            }
    }
    

    Change userInfo key to whatever name have you used for storing first name in Firestore. For example if you named your document field firstName then userInfo dictionary key must be firstName.