使用swift访问firebase中特定键的值

时间:2017-10-27 00:15:07

标签: ios swift firebase firebase-realtime-database

我有以下firebase结构。Firebase Structure

"用户"是根,键是" Uid"。如何为给定的" Uid"?

访问密钥的特定值

示例:我想检索" mobileno"特定用户与" Uid"如M5j80aAlmCS3Jcbh0aA3T4Tfzxv1。

3 个答案:

答案 0 :(得分:2)

要获取用户的个人资料信息,请使用FIRUser实例的属性。例如:

let user = Auth.auth().currentUser
if let user = user {
  // The user's ID, unique to the Firebase project.
  // Do NOT use this value to authenticate with your backend server,
  // if you have one. Use getTokenWithCompletion:completion: instead.
  let uid = user.uid
  let email = user.email
  let photoURL = user.photoURL
  // ...
}

有关详细信息,请参阅Firebase Documentation

答案 1 :(得分:1)

如果是您的uid(或用户):

if let userUID = Auth.auth().currentUser?.uid{
    %firebaseReferenceVariable%.child("Users/\(userUID)").observeSingleEvent(of: .value, with: { snapshot in 
        if snapshot.value is NSNull{
             //handles errors
             return
        }
        else{
             if let selectedUser = snapshot.value as? NSDictionary //OR [Stirng: Any]{
                 let mobileno = selectedUser["mobileno"] as! String
                 //Do something with mobileno
             }
        }

   })
}

您可以使用firebase引用调用中的任何字符串值替换变量userUID,它将获得该用户 - 我建议(如果您尝试从应用程序访问这些用户)以填充tableView或collectionView(某种类型)列表)与所有用户。您还可以获取所有用户并循环浏览所需的用户(如果您有一个布尔变量来显示此用户,请说明。)

答案 2 :(得分:1)

看一下我使用Observe Block的下面的代码,因为每次在聊天应用程序中更新数据时我都需要获取数据。所以你可以利用观察单个事件来获取数据,最后也可以删除观察者。

   Database.database().reference().child("users").child(your Key value).observe(.value, with: { (snapshot) in

         if snapshot.exists(){

            print(snapshot)

            if let snapDict = snapshot.value as? [String:AnyObject] {

                //here you can get data as string , int or anyway you want 
                self. mobilenoLabel.text = snapDict["mobileno"] as? String


            }

        }

    })