从当前用户的Firebase Swift获取文档

时间:2019-11-06 21:13:20

标签: swift firebase firebase-realtime-database google-cloud-firestore firebase-authentication

我正在尝试从中获取名字: enter image description here

用户已登录,我可以访问他的uid,但是我无法获取属于该用户的文档,这就是我要这样做的方式:

    private func getDocument() {

        var userID = Auth.auth().currentUser?.uid
            userID = String(userID!)

        var currentUser = Auth.auth().currentUser


//         Get sspecific document from current user
        let docRef = db.collection("users").document("bnf2s3RURUSV2Oecng9t")

        // Get data
        docRef.getDocument { (document, error) in
            if let document = document, document.exists {
                let dataDescription = document.data().map(String.init(describing:)) ?? "nil"
                print("Document data: \(dataDescription)")
            } else {
                print("Document does not exist")
            }
        }
    }

如果您注意到了,如果我手动放置“ bnf2s3RURUSV2Oecng9t”,它将访问数据,但是要知道的是“ bnf2s3RURUSV2Oecng9t”是什么,所以我可以将其放在该硬编码变量的顶部。目标是能够获得当前用户的名字:)

1 个答案:

答案 0 :(得分:1)

问题是您当前通过身份验证的用户uid与文档uid不同。因此,通常,如果这些ID相同,您将执行以下操作:

    private func getDocument() {
        //Get specific document from current user
        let docRef = Firestore.firestore().collection("users").document(Auth.auth().currentUser?.uid ?? "")

        // Get data
        docRef.getDocument { (document, error) in
            if let document = document, document.exists {
                let dataDescription = document.data()
                print(dataDescription?["firstname"])
            } else {
                print("Document does not exist")
            }
        }
    }

但是在您的情况下,您需要这样做,因为这些值并不相同。

   private func getDocument() {
        //Get sspecific document from current user
        let docRef = Firestore.firestore().collection("users").whereField("uid", isEqualTo: Auth.auth().currentUser?.uid ?? "")

        // Get data
        docRef.getDocuments { (querySnapshot, err) in
            if let err = err {
                print(err.localizedDescription)
                return
            } else if querySnapshot!.documents.count != 1 {
                print("More than one documents or none")
            } else {
                let document = querySnapshot!.documents.first
                let dataDescription = document?.data()
                guard let firstname = dataDescription?["firstname"] else { return }
                print(firstname)
            }
        }
    }