Mathias Erligmann
Mathias Erligmann

Reputation: 25

Retrieving data from a query in Firebase for Swift

I have this database structure :

Users
   user1
      username : username1
      otherdata : otherdata1

   user2
      username : username2
      otherdate : otherdata2

What I'm looking for is to display the usernames of my user in a tableview when one user use a uisearchbar on top of the table view. I managed to print the data of each users using this code :`

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
    ref = Database.database().reference()
    let strSearch = searchBar.text
    ref.child("Users").queryOrdered(byChild: "username").queryStarting(atValue: strSearch).queryEnding(atValue: strSearch! + "\u{f8ff}").observeSingleEvent(of: .value, with: { (snapshot) in
        for snaps in snapshot.children {
            print(snaps)
        }
    }) { (err) in
        print(err)
    }
}

But I'm stuck because I don't know how to retrieve just the username for each user. Can someone tell me how to do it ?

Upvotes: 0

Views: 408

Answers (1)

Nishant Bhindi
Nishant Bhindi

Reputation: 2252

 func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        ref = Database.database().reference()
        let strSearch = searchBar.text
        ref.child("Users").queryOrdered(byChild: "username").queryStarting(atValue: strSearch).queryEnding(atValue: strSearch! + "\u{f8ff}").observeSingleEvent(of: .value, with: { (snapshot) in
            var fetchedList = snapshot.value as! [AnyObject]
            for obj in fetchedList { 
            print(obj["username"] as? String) 
            print(obj["otherdata"] as? String) 
       }

        }) { (err) in
            print(err)
        }
    }

you will get response like this

[{username : username1}, {username : username2}]

Upvotes: 1

Related Questions