简体   繁体   English

如何使用 Firebase Firestore 在 Swift 中获取当前用户的文档 ID?

[英]How to get current user's document id in Swift using Firebase Firestore?

let db = Firestore.firestore()
    let currentUser = Auth.auth().currentUser
    
    guard currentUser != nil else {return}
    let docRef = db.collection("UserProfiles").document("sWD6Sr11yimSFrpZ9B0m")
    
    docRef.getDocument { document, error in

        guard error == nil else {return}

        guard let name = document?.get("name") as? String else {return}
        guard let lastname = document?.get("lastname") as? String else {return}
        self.nameLabel.text = name+" "+lastname

    }

Manual display of current user's documentID = "sWD6Sr11yimSFrpZ9B0m"手动显示当前用户的 documentID = "sWD6Sr11yimSFrpZ9B0m"

How can I get the document ID of the current user automatically?如何自动获取当前用户的文档 ID?

Saved document IDs保存的文档 ID

guard let userId = Auth.auth().currentUser?.uid else {return}

will return current user id who is logged in将返回当前登录的用户 ID

you can get all document ids of a collection but not current!您可以获得集合的所有文档 ID,但不是当前的! firebase doesn't know what is current user document or id. firebase 不知道当前用户文档或 ID 是什么。 You just get current user uid and save document with uid and get it with uid您只需获取当前用户 uid 并使用 uid 保存文档并使用 uid 获取它

 db.collection("Seeker").getDocuments { querySnapshot, error in
                guard let snapshot = querySnapshot, error == nil else {return}
                let documentIDs = snapshot.documents.map({$0.documentID})
                print(documentIDs)
            }

this is how you get all documents ids ...这就是您获取所有文档 ID 的方式...

if you want to keep track document id如果您想跟踪文档 ID

self.db.collection("Seeker").document(userId).setData([
                        "email": email,
                        "role" : userType.title
                    ])

so you can get Seeker with his user id as document id所以你可以用他的用户 id 作为文档 id 来获取 Seeker

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM