2

I am using Firebase and my database looks like this:

Users
   user1
      email: "example1@test.com"
      password: "pass1"
      display name: "Name1"
   user2
      email: "example2@test.com"
      password: "pass2"
      display name: "Name2"

How can I retrieve the email for example, given the display name using Swift 3? (e.g., if I know Name1, the retrieved data will be example1@test.com.)

AL.
  • 36,815
  • 10
  • 142
  • 281
alecs09
  • 45
  • 6
  • Related: https://stackoverflow.com/questions/43971814/firebase-querying-for-unique-username-swift – Nirav D Jun 19 '17 at 11:15
  • I understand how to get all the data where I find de display name, but I don't know how to reach the exact field with the email. I mean what do I need to write besides "snapshot.value" ? @NiravD – alecs09 Jun 19 '17 at 14:21
  • @begood Please check if my answer below is what you were after... – Paulo Mattos Jun 19 '17 at 14:26

2 Answers2

1

Use firebase as below

let dbstrPath : String! = "Users/user1"
self.dbRef.child(dbstrPath).observeSingleEvent(of: .value, with: { (snapshot) in
    if snapshot.exists(){
        print(snapshot.value!)
        // Here you got user value in dict
    }
})
dahiya_boy
  • 9,298
  • 1
  • 30
  • 51
0

Implement the following helper function:

func queryEmail(of displayName: String, completion: @escaping (String?) -> Void) {
    let users = FIRDatabase.database().reference().child("Users")
    let query = users.queryOrdered(byChild: "display name").queryEqual(toValue: displayName)
    query.observeSingleEvent(of: .value) {
        (snapshot: FIRDataSnapshot) in
        guard snapshot.exists() else {
            completion(nil)
            return
        }
        let users = snapshot.children.allObjects as! [FIRDataSnapshot]
        precondition(users.count == 1, "Display name isn't unique!")
        let userProperties = users.first!.value as! [String: Any]
        completion(userProperties["email"] as? String)
    }
}

and use it like this:

queryEmail(of: "Name1") {
    (email) in
    if let email = email {
        print("Name1 email is \(email)")
    } else {
        print("Email not found")
    }
}
Paulo Mattos
  • 18,845
  • 10
  • 77
  • 85