【问题标题】:How to fetch user data from cloud firestore如何从 Cloud Firestore 中获取用户数据
【发布时间】:2020-06-27 17:56:32
【问题描述】:

有人可以帮助我从我在 firebase 中的集合中检索“名字”数据吗?我想将用户配置文件上的用户名显示到一个名为“nameLable”的 UILable,但我不确定如何?

如果有人可以提供帮助,我希望每个用户都能在个人资料页面上看到他们的名字!我正在使用 Cloud Firestore。

【问题讨论】:

    标签: swift firebase google-cloud-firestore uilabel


    【解决方案1】:

    您可以使用以下代码获取文档列表中每个用户的名字。

    func getName(Completion: @escaping((String) -> ())) {
        let collectionRefernce:CollectionReference!
        let db = Firestore.firestore()
        collectionRefernce = db.collection("members")
        collectionRefernce.getDocuments { (querySnapshot, error) in
            if error != nil {
                print("Error is \(error!.localizedDescription)")
            } else {
                guard let snapshot = querySnapshot else { return }
                for document in snapshot.documents {
                    guard let myData = document.data() else { return }
                    let firstname = myData["firstName"] as? String ?? "No Name Found"
                    Completion(firstname)
                }
            }
        }
    }
    

    这将检索每个用户的firstname。调用函数:

    getName{ (name) in
        label.text = name
      }
    

    如果您想检索当前登录用户的名字,请使用下面的代码

    let id = Auth.auth().currentUser!.uid
     func getName(Completion: @escaping((String) -> ())) {
        let DocRefernce:DocumentReference!
        let db = Firestore.firestore()
        DocRefernce = db.collection("members").document(id)
        DocRefernce.getDocument { (docSnapshot, error) in
            if error != nil {
                print(error!)
            } else {
                guard let snapshot = docSnapshot, snapshot.exists else { return }
                guard let data = snapshot.data() else { return }
                let firstname = data["firstName"] as? String ?? "No name"
                Completion(firstname)
            }
        }
    
    }
    

    然后像这样在viewDidLoad中调用它

    getName{ (name) in
      label.text = name
     }
    

    【讨论】:

    • @Zack,我的荣幸!请标记我的答案。我会很感激的!
    • 我试过了,但它说“感谢您的反馈!声望低于 15 的人的投票会被记录下来,但不要更改公开显示的帖子得分。”
    • 我的答案上有'✓'标志。只需检查它就会变成绿色。
    猜你喜欢
    • 1970-01-01
    • 2020-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-30
    • 2021-02-23
    相关资源
    最近更新 更多