-2

JSON ImageI want to query like: If I give email, then I have to get the ID. At the moment I can fetch email or ID but I need solution for below example.

For example 1) if I give [email protected] then I need it's ID as 123.

How can I achieve this in swift?

This is my JSON file:

{
   "ID": 123,
   "Membership": 1234,
   "title": "Mr.",
   "firstname": "kumar",
   "lastname": "sandeep",
   "email": "[email protected]",
   "membrshipstatus": "Active",
   "volunteer": "Yes",
   "creationDate": "2016-12-27 "
 },

{
   "ID": 452,
   "Membership": 4531,
   "title": "Mr.",
   "firstname": "kumar",
   "lastname": "sandeep",
   "email": "[email protected]",
   "membrshipstatus": "Active",
   "volunteer": "Yes",
   "creationDate": "2016-11-17 "
 },

This is my Swift code:

    import UIKit
    import Firebase
    import FirebaseAuth

    class ViewController: UIViewController {

        @IBOutlet weak var emailofUser: UITextField!
        @IBOutlet weak var passwordofUser: UITextField!
        var ref:FIRDatabaseReference! //created a variable ref of type firebase database reference
        var databaseHandle:FIRDatabaseHandle? //to handle to database listener like to stop or start it


        var postdata = [String]?()
        var postall = [[String:String]]()


        override func viewDidLoad() {
            super.viewDidLoad()

            //set firebase reference
            ref = FIRDatabase.database().reference()

ref.child("1").child("email").observeEventType(.Value, withBlock: { snapshot in

            let emailid = snapshot.value as? String

            print(emailid)
        })

ref.child("1").child("ID").observeEventType(.Value, withBlock: { snapshot1 in

            let userID = snapshot1.value as? Int

            print(userID)
        })

            ref.queryOrderedByValue().observeEventType(.ChildAdded, withBlock: { snapshot2 in
                if let parentname = snapshot2.value as? Int {
                    print("The \(snapshot2.key) dinosaur's score is \(parentname)")
                }
            })
        }
    }

Swift Code related to this JSON image:

override func viewDidLoad() {
        super.viewDidLoad()



            //set firebase reference
        ref = FIRDatabase.database().reference()

        let userRef = ref.child("1")

        //let queryRef = userRef.queryOrderedByChild("email").queryEqualToValue("[email protected]")


        userRef.queryOrderedByChild("email").queryEqualToValue("[email protected]").observeEventType(.Value, withBlock: { snapshot in

            for child in snapshot.children{

            let snap = child as! FIRDataSnapshot

                let userDict = snap.value as! [String:Any]

                let userId = userDict["ID"]
                let lastname = userDict["lastname"]
                print("\(userId!)  \(lastname!)")


            }
                    })
3
  • 2
    Possible duplicate of Parse JSON response with Swift 3 Commented Feb 16, 2017 at 17:06
  • Sorry my question is different. For example 1) if I give [email protected] then I need it's ID as 123. How can I achieve this in swift? Commented Feb 16, 2017 at 19:08
  • This is a basic query in Firebase. Please see my answer and also read up on Working with Lists in particular the Sorting and Filtering data section. Commented Feb 17, 2017 at 0:05

1 Answer 1

1

You should be using the uid of the user to store data in the users node in general. Assuming your users node is called /users... like this

users
  uid_0
   "ID": 123,
   "Membership": 1234,
   "title": "Mr.",
   "firstname": "kumar",
   "lastname": "sandeep",
   "email": "[email protected]"
  uid_1
   "ID": 452,
   "Membership": 4531,
   "title": "Mr.",
   "firstname": "kumar",
   "lastname": "sandeep"
   "email": "[email protected]"

here's the query to get the data you are asking about

let usersRef = ref.child("users")
let queryRef = usersRef.queryOrdered(byChild: "email")
                       .queryEqual(toValue: "[email protected]")
queryRef.observeSingleEvent(of: .value, with: { (snapshot) in

     for child in snapshot.children {
          let snap = child as! FIRDataSnapshot
          let userDict = snap.value as! [String: Any]
          let userId = userDict["ID"]
          let lastname = userDict["lastname"]
          print("\(userId!)  \(lastname!)")
      }
})

and the result prints:

123  sandeep
Sign up to request clarification or add additional context in comments.

4 Comments

Hi Jay, I tried this code, but its not printing anything. please help.
@SandeepKumat I copy and pasted that code from a working project. Make sure your Firebase structure matches what's in the answer. You didn't include a full snippet of your JSON structure in the original question so I had to assume a structure.
Hi Jay,I just added JSON image and code according to that JSON structure. Please verify my code. Thank you a lot.
@SandeepKumat this is probably the issue let userRef = ref.child("1") but the json structure is still incomplete without a parent node.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.