获取当前用户的名字 cloud firebase swift

grab the current users first name cloud firebase swift

我有一个存储用户的 Firebase Auth,但它也在 Cloud Firestore 数据库中构建了一个用户集合。我可以获取用户的名字,但我遇到的问题是它始终是最后添加的用户。

这是我在 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!"
                }
            }
        }
    }
}

在 firebase 云中,我的用户是这样存储的

开始收集是"users"

添加文档是autoID

那么合集就是

名字 "Jane"

姓氏 "Doe"

uid "IKEPa1lt1JX8gXxGkP4FAulmmZC2"

有什么想法吗?

当您遍历所有用户文档的列表时,它将在标签上显示最后一个用户的 firstName。您可能希望如下所示显示第一个用户,

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

如果列表中的 uiduserId

相同,则可能是当前用户
if let currentUserDoc = snapshot?.documents.first(where: { ([=11=]["uid"] as? String) == userId }) {
   var welcomeName = currentUserDoc["firstname"] as! String
   self.welcomeLabel.text = "Hey, \(welcomeName) welcome!"
}

您的用户集合应该如下所示

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

然后,当用户进行身份验证时,您将知道他们的uid,因此您可以直接从Firestore 中获取信息而无需查询。

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!")
            }
        })
    }
}

如果用户 William 登录,这将打印到控制台

嗨,欢迎威廉!