使用Swift在Firebase中让孩子们的孩子

时间:2019-05-14 20:25:33

标签: swift firebase-realtime-database

我有一个简单的firebase数据库,我需要从中获取子级值。如何获得子级字段值?这是我的数据库:

Users

 -LddrOHGdBf_GcPrcvYn

    FirstName: Mike

    LastName: Smith

    username: m@m.com

我已经到处都是堆栈溢出,似乎没有人可以回答这个问题,但是我知道这一定很容易。

import UIKit
import FirebaseDatabase

class CustProfileViewController: UIViewController {
var ref: DatabaseReference?
var tempName = ""
var tempFirstName = ""
@IBOutlet weak var username: UITextField!
@IBOutlet weak var firstName: UITextField!
@IBOutlet weak var editAddressButton: UIButton!
override func viewDidLoad() {
    super.viewDidLoad()
    ref = Database.database().reference()
    username.text = "m@m.com"
}

@IBAction func editAddressButtonPressed(_ sender: Any) {
    self.ref?.child("Users").queryOrdered(byChild: "username").queryEqual(toValue: username.text!).observe(.value, with: { (snapShot) in
        if (snapShot.value! is NSNull) {
        print("nothing found")
    } else {
        print("found it!")
            print(snapShot)
            let snapShotValue = snapShot.value as! NSDictionary
            let fName = snapShotValue["FirstName"] as? String
            self.firstName.text = fName
            print(self.firstName.text!)

        }
    })
}

}

我希望firstName文本框填充fName,但它返回的是nil值。

1 个答案:

答案 0 :(得分:0)

您可以尝试

@IBAction func editAddressButtonPressed(_ sender: Any) {
    self.ref?.child("Users").queryOrdered(byChild: "username").queryEqual(toValue: username.text!).observe(.value, with: { (snapShot) in
    if !snapShot.exists() {
         print("nothing found")
    } else {
        print("found it!")
            print(snapShot)
            let snapShotValue = snapShot.value as! [String:[String:Any]]
            Array(snapShotValue.values).forEach {
               let fName = $0["FirstName"] as! String 
               print(fName)
            }

        }
    })
}