0

I have a simply firebase database that I need to get the children values from. How can I obtain the children field values? Here is my database:

Users

 -LddrOHGdBf_GcPrcvYn

    FirstName: Mike

    LastName: Smith

    username: m@m.com

I have been all over stack overflow and nothing seems to answer this question, but I know it must be easy.

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!)

        }
    })
}

}

I am expecting the firstName text box to be populated with the fName, but it is returning a nil value.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Michael R
  • 93
  • 1
  • 8

1 Answers1

0

You can try

@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)
            }

        }
    })
}
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87