显示标签中某个firebase子项的值

时间:2017-06-22 01:54:52

标签: ios swift firebase firebase-realtime-database

我想在标签中显示某个firebase子项的数据。

我的代码如下:

let ref = FIRDatabase.database().reference()

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

let users = snapshot.value as! [String : AnyObject]

               for (_, value) in users {
                   if let fullName = value["name"] as? String {
                       if let role = value["role"] as? String {
                           if let mtid = value["mtid"] as? Int {

                               let userNAME = fullName
                               let userROLE = role
                               let userMTID = mtid

                                 print("ID: \(mtid) and NAME: \(fullName) and ROLE: \(role)")

                                  self.mtidLabel.text = userMTID
                                  self.roleLabel.text = userROLE
                                  self.nameLabel.text = userNAME
                           }
                       }
                   }
               }
})

我的数据库如下:

 users:
    - 1234567
        * mtid: 1234567
        * name: "John Smith"
        * role: "coordinator"
    - 2278433
        * mtid: 2278433
        * name: "John Doe"
        * role: "developer"
    - 2317894
        * mtid: 2317894
        * name: "Doe Smith"
        * role: "crew"

基本上,如果用户在文本框中输入一串数字,例如2317894,我希望它将孩子的mtid值显示为2317894,名称为" Doe Smith"以及#34; crew"全部在单独的文本框中。

当我使用上面的代码时,它只选择其中一个选项来显示并将所有选项打印到控制台。

有人知道我做错了吗?

1 个答案:

答案 0 :(得分:0)

我已经回答了我自己的问题。 我在代码中更改了以下内容

删除了for (_, value) in users

let users = snapshot.value as! [String : AnyObject]更改为let users = snapshot.value as! NSDictionary

.child(self.TEXTBOX_THAT_CONTAINS_CHILD_NUMBER_EG_1234567.text!)ref.child("users")

之间添加了.queryOrderedByKey()

最终守则:

ref.child("users").child(self.TEXTBOX_THAT_CONTAINS_CHILD_NUMBER_EG_1234567.text!).queryOrderedByKey().observeSingleEvent(of: .value, with: { (snapshot) in

  print(snapshot)
  let snapshotValue = snapshot.value as! NSDictionary
     if let fullName = snapshotValue["name"] as? String {
      if let role = snapshotValue["role"] as? String {
       if let mtid = snapshotValue["mtid"] as? Int {
         let userNAME = fullName
         let userROLE = role
         let userMTID = mtid
         print("ID: \(mtid) and NAME: \(fullName) and ROLE: \(role)")

         self.mtidLabel.text = userMTID
         self.roleLabel.text = userROLE
         self.nameLabel.text = userNAME
       }
      }
     }

})