请求用户名时,Firebase快照返回null

时间:2018-06-02 15:15:08

标签: ios swift firebase firebase-realtime-database firebase-authentication

我正在制作Instagram克隆,并希望获得用户显示的用户名。信息位于firebase的Database部分,我试图通过快照完成,但它总是返回。

fileprivate func fetchUser() {
    guard let uid = Auth.auth().currentUser?.uid else { return }


    Database.database().reference().child("users").child(uid).observeSingleEvent(of: .value, with: { (snapshot) in
        print(snapshot.value ?? "")
    }) { (err) in
        print("Failed to fetch user:", err)
    }
}

代码格式间隔奇怪,但这就是代码。我没有让Childs正确,或者发生了什么?

编辑:此处还有Firebase Db的快照。Firebase screenshot

1 个答案:

答案 0 :(得分:2)

试试这个:

guard let uid = Auth.auth().currentUser?.uid else { return }
let reference = Database.database().reference()
reference.child("users").child(uid).observeSingleEvent(of: .value, with: { (snapshot) in

    guard let dictionary = snapshot.value as? [String: Any] else { return }

    let username = dictionary["username"] as? String

    print(username ?? "")

}, withCancel: nil)