dantheputzer
dantheputzer

Reputation: 35

Swift: Searching Firebase Database for Users

I have been looking all over the internet and Stack overflow but haven't found anything that I understood well enough to implement into my solution. There are many similar questions out there but none of the proposed solutions worked for me, so I'll ask you guys.

How do I search my Firebase database for usernames in swift? In my app I have a view that should allow the user to search for friends in the database. Results should be updated in real time, meaning every time the user types or deletes a character the results should update. All I have so far is a UISearchBar placed and styled with no backend code.

Since I don't really know what is needed to create such a feature it would be cool if you guys could tell me what you need to tell me exactly what to do. (Database Structure, Parts of Code...). I don't want to just copy and paste useless stuff on here.

I would really appreciate the help.

EDIT:

This is my database structure:

"users"
    "uid"   // Automatically generated
        "goaldata"
             "..."   // Not important in this case
        "userdata"
             "username"
             "email"
             "country"
             "..."  // Some more entries not important in this case

Hope I did it right, didn't really know how to post this on here.

Upvotes: 3

Views: 5402

Answers (1)

Jen Jose
Jen Jose

Reputation: 4035

Suppose the Firebase structure is like this

Example 1 :

users
    -> uid
        ->otherdata
        ->userdata
            ->username : "jen"
            -> other keys

    -> uid2
        ->otherdata
        ->userdata
            ->username : "abc"
            -> other keys

And to query based on username, we need to query on queryOrdered(byChild: "userData/username"). queryStarting & queryEndingAt , fetches all the names starting from "je" and this "\uf8ff" signifies * (any) .

let strSearch = "je"
baseRef.child("users").queryOrdered(byChild:  "userData/username").queryStarting(atValue: strSearch , childKey: "username").queryEnding(atValue: strSearch + "\u{f8ff}", childKey: "username").observeSingleEvent(of: .value, with: { (snapshot) in
       print(snapshot)
    }) { (err) in
      print(err)
}

If the username is directly below the users node, then try this

Example 2 :

users
    -> uid
         ->username : "jen"
         -> other keys

    -> uid2
         ->username : "abc"
         -> other keys

The query will be restructured as below,

 let strSearch = "je"
 baseRef.child("users").queryOrdered(byChild:  "username").queryStarting(atValue: strSearch).queryEnding(atValue: strSearch + "\u{f8ff}").observeSingleEvent(of: .value, with: { (snapshot) in

  print(snapshot)

})

Please note this method is case-sensitive . The search results for search String = "je" and "Je" will be different and the query will match the case.

Upvotes: 8

Related Questions