Search code examples
iosfirebaseswift3firebase-realtime-databasedata-retrieval

How to retrieve specific firebase data results based on users preference in IOS?


I am new to firebase just learning, I want to create a filter option for users to pull a specific informations about other users for my application. Therefore, I want to retrieve certain firebase users data based on users selections to my tableview. For example, if a user selected (Male,USA,High School) I would want to display all users names whose Country = "USA", gender = "Male" and school = "High School" to my tableview. I have tried this code below for just one option (Gender) but I don't know how to do it for the other options Queries (School,Country)enter image description here. would appreciate if you could show me how to do it. thanks

  let ref = Database.database().reference()

  ref.child("users").queryOrdered(byChild: "Gender").queryEqual(toValue: genderLbl.text) // "genderLbl.text = "Male"

Solution

  • As you probably know already Firebase is a no-sql database system, which means you can't retrieve data like you do in a sql base with queries, there's no relations between elements. You must think about your model in terms of what data you want to retrieve.

    It's your job to create a path where you put a reference (when creating a user) to all the users from USA, male, in highschool, named James, like :

    - Users
    - UsersByCountry
        - USA
             - Male
                 - HighSchool
                     - James
                         - 846efz-ezf4z6e-zef6ze4f8 (id of the user)
                         - 846efz-315da3z-az5z5e422
                         - 846efz-azd5a7z-dafg4g5ej
                     - Alfred
                     - Robert
                 - ElementarySchool
             - Female
        - UK
        - Canada
    

    If you have a lot of relations in your model and your service requires to retrieve a lot of connected datas, I advise you to change for a sql database.