如何使用Swift从Firebase中的当前用户检索数据?

时间:2017-05-16 12:46:39

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

我正在尝试使用swift代码从firebase获取当前用户的firstname。下面是我的JSON文件和swift代码。但它没有检索名字。请建议

JSON structure JSON:

Swift代码:

  if FIRAuth.auth()?.currentUser != nil{

        let queryRef = FIRDatabase.database().reference().child("expatsappmembers")


        let userID : String = (FIRAuth.auth()?.currentUser?.uid)!
        print("Current user ID is" + userID)

        queryRef.child("uid").child(userID).observeSingleEvent(of: .value, with: {(snapshot) in
            print(snapshot.value)

            let userName = (snapshot.value as! NSDictionary)["firstname"] as! String
            print(userName)


        })

    }

1 个答案:

答案 0 :(得分:0)

从Swift 3中的Firebase获取值略有不同

正确的方法是:

ref.child("expatsappmembers").queryOrderedByKey().observeSingleEvent(of: .value, with: { (snapshot) in

  // Get user value
  let value = snapshot.value as? NSDictionary
  let firstName = value?["firstname"] as? String

  // ...
  }) { (error) in
    print(error.localizedDescription)
}