1

I work with firebase database, I have the following data,

enter image description here

I need to get all groups names (GName) of a user by his phoneNum, i.e. all groups of specific user, How can I get that in swift 4?

KENdi
  • 7,576
  • 2
  • 16
  • 31
Ali A. Jalil
  • 873
  • 11
  • 25

1 Answers1

1

You should consider restructuring your data. If a user belongs to more than one group in your application then you'll probably have to duplicate your user node for every group the user belongs to in your data structure. You can create another JSON object that holds all of the groups that a user belongs to. Here is a sample JSON for you:

{
    "users": [{
        "xyz123": {
            "userId": "xyz123",
            "username": "user1",
            "phoneNum": "123456",
            "groups": [{
                "groupId": 1,
                "groupName": "aaa"
            }, {
                "groupId": 2,
                "groupName": "bbb"
            }]
        }
    }]
}

As for filtering with the phone number, you can get all users inside a list and filter the result with the phone number criteria

result = result.filter({item.phoneNum == "123456"})

or get phone number of the user to a upper level, call .child() method with the phone number criteria and fetch the specific user.

Also take a look at structuring data part at firebase documentation.

https://firebase.google.com/docs/database/ios/structure-data

Hope that helps.

Mert Ozdal
  • 82
  • 5
  • Mert Ozdal, Many thanks for your respond, But how can I set values of "groups" in the way you are suggested, I put is as following but it's not worked for me, func toAnyObject() -> Any { return [ "lat": lat, "lon": lon, "title": title, "imageName": imageName, "phoneNum":phoneNum, "admin": admin , "Groups": ["gId":groups.map { $0.id }, "gName":groups.map { $0.name }] ] } – Ali A. Jalil Sep 22 '18 at 16:52
  • Your Groups array's JSON notation seemed wrong. You have to put JSON objects inside arrays. For example [{"gId":groups.map { $0.id }, "gName":groups.map { $0.name }}] is a correct Groups array with one element inside it which is {"gId":groups.map { $0.id }, "gName":groups.map { $0.name }} . You also have to do the same to User object that is in an array too. You can also try to validate your JSON with a json validator. – Mert Ozdal Sep 25 '18 at 21:12
  • I try that before, the map function produce an array of ids or gNames, it's not produce a single value. – Ali A. Jalil Sep 26 '18 at 05:37