grab the current users first name cloud firebase swift

柔情痞子 提交于 2020-03-03 08:41:26

问题


I have a Firebase Auth that stores the users, but it also builds a collection of users in the Cloud Firestore database. I can grab the users first name, but the problem I have is that it is always the last user that was added.

here is my function in swift

func welcomeName() {

    let db = Firestore.firestore()
    if let userId = Auth.auth().currentUser?.uid {

    var userName = db.collection("users").getDocuments() { (snapshot, error) in
        if let error = error {
            print("Error getting documents: \(error)")
    } else {
        //do something
            for document in snapshot!.documents {
        var welcomeName = document["firstname"] as! String
        self.welcomeLabel.text = "Hey, \(welcomeName) welcome!"
                }
            }
        }
    }
}

in firebase cloud my users are stored as so

start collection is "users"

add document is the autoID

then collection is

firstname "Jane"

lastname "Doe"

uid "IKEPa1lt1JX8gXxGkP4FAulmmZC2"

any ideas?


回答1:


As you are looping through a list of all user documents so it will show last user's firstName on the label. You might want to show the first user as below,

if let firstUserDoc = snapshot?.documents.first {
   var welcomeName = firstUserDoc["firstname"] as! String
   self.welcomeLabel.text = "Hey, \(welcomeName) welcome!"
}

Or may be this for current user if uid in the list is same as userId,

if let currentUserDoc = snapshot?.documents.first(where: { ($0["uid"] as? String) == userId }) {
   var welcomeName = currentUserDoc["firstname"] as! String
   self.welcomeLabel.text = "Hey, \(welcomeName) welcome!"
}



回答2:


You're users collection should look like this

users (collection)
   uid_0 (document that's the users uid)
      first_name: "William"
   uid_1
      first_name: "Henry"
   uid_2

Then, when the user authenticates, you will know their uid, so you can directly get the information from Firestore without a query.

func presentWelcomeMessage() {
    if let userId = Auth.auth().currentUser?.uid {
        let collectionRef = self.db.collection("users")
        let thisUserDoc = collectionRef.document(userId)
        thisUserDoc.getDocument(completion: { document, error in
            if let err = error {
                print(err.localizedDescription)
                return
            }
            if let doc = document {
                let welcomeName = doc.get("first_name") ?? "No Name"
                print("Hey, \(welcomeName) welcome!")
            }
        })
    }
}

If user William logs in, this will be printed to the console

Hey, William welcome!



来源:https://stackoverflow.com/questions/58470066/grab-the-current-users-first-name-cloud-firebase-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!