Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating class for Firebase DataStructure in Swift

I am new to firebase, a Firebase structure was created for me to work on, what i want to do basically is to list all users the FirebaseDB.

I want to create a corresponding class in swift to the firebase data structure below.

 "users" : {
    "A654tdC5uBPoKQzJnpZIpwOfsaJ3" : {
      "groups" : {
        "-KZ7fl3I4W7YWuGk6l9k" : true,
        "-KclzmvvJF54cAg14P92" : true,
        "-KclzpzrJOhCOWL5_jvw" : true,
        "-Kcm33N1B_oiVYrQWh3n" : true,
        "-Kcm3GfRaaGfztEBmflp" : true
      },
      "location" : {
        "coordinates" : [ 6.59086, 3.3914267 ],
        "name" : "Oyebanjo Solarin Street, Lagos",
        "visibility" : true
      },
      "photoUrl" : "http://pbs.twimg.com/profile_images/511567946351923201/YBqqKc78_normal.jpeg",
      "username" : "Kamiye",
      "visibilityToSelectContacts" : {
        "contacts" : {
          "gFTCpzgSJDOsrVKWbAJp0Z1JFXp1" : true,
          "rRxT6x87kgSjTwZfa7M8ZwzdFkC3" : true
        },
        "visibility" : true
      }
    },

This is what i have tried and its not working

class LContact {

var visibliityToSelectedContacts: VisibilityToSelectContacts?
var photoUrl: String?
let username: String
var location: LALocation?
var groudId = [String]()


init (value: [String: Any] ) {
    self.username = value["username"] as! String
    self.photoUrl = value["photoUrl"] as? String
    self.location = LALocation(value: value["coordinates"] as? [String:Any] ?? [:])
    self.groudId = (value["groups"] as? [String])!
  }
}

class VisibilityToSelectContacts {

var contacts = [String]()
var visibility: Bool

init(value: [String: Any]) {
    self.contacts = [value["contacts"] as! String]
    self.visibility = value["visibility"] as! Bool
  }
}

struct LALocation {

var long: Double
var lat: Double
var address: String!
var visibility: Bool!

init(long: Double, lat: Double, address: String?, visibility: Bool) {
    self.long = long
    self.lat = lat
    self.address = address
    self.visibility = visibility
}

init?(value: [String: Any]) {
    guard let long = value["0"] as? Double,
        let lat = value["1"] as? Double else {return nil}
    self.long = long
    self.lat = lat
    self.address = value["name"] as? String
    self.visibility = value["visibility"] as? Bool
   }
}
like image 767
SimpuMind Avatar asked Feb 15 '17 22:02

SimpuMind


People also ask

Which data structure is used in Firebase?

All Firebase Realtime Database data is stored as JSON objects. You can think of the database as a cloud-hosted JSON tree. Unlike a SQL database, there are no tables or records. When you add data to the JSON tree, it becomes a node in the existing JSON structure with an associated key.

Is Firebase better than MongoDB?

MongoDB is a more robust document database known for high performance and best-in-class security, and has several advantages over Firebase. For example, MongoDB can be operated on-premise or in the cloud (using MongoDB Atlas, or self-managed cloud MongoDB), while Firebase is purely a cloud database service.

Can I use SQL with Firebase?

Firebase SQL Server Integration is a process that helps you quickly transfer data between Firebase and SQL Server. It plays a vital role when you are designing applications or websites on Firebase and are using SQL Server as your database.


1 Answers

Let me get you going with some code that may help. It's not the entire class but all of the concepts are there. I also am using a simplified Firebase structure, but again, the concepts are the same:

Here's the Firebase structure

users
  a_uid
    email: "some email"
    groups
      group_1: true
      group_2: true
    location
      coords: "[52.5, 67.1]"
      name: "Oyebanjo Solarin Street, Lagos"
      visibility: true
    username: "some username"

First there's appears to be a Location for each user thats lends itself to being a structure.

   struct LocationStruct {
        var coords: String?
        var name: String?
        var visibility: Bool?
    }

We then use that structure within our user class. In this example, we pass in a snapshot for a single user to initialize the class and deconstruct it to populate the class variables.

class UserClass {
    var email = ""
    var username = ""
    var groupsDict: [String: Any]
    var loc = LocationStruct()

    init(snap: FIRDataSnapshot) {

        let userDict = snap.value as! [String: Any]

        self.email = userDict["email"] as! String
        self.username = userDict["username"] as! String

        self.groupsDict = userDict["groups"] as! [String: Any]

        let locationDict = userDict["location"] as! [String: Any]
        self.loc.coords = locationDict["coords"] as? String
        self.loc.name = locationDict["name"] as? String
        self.loc.visibility = locationDict["visibility"] as? Bool
    }
}

Here's the code to read in a single user and populate a UserClass

    ref.child("users").child("a_uid")
                      .observeSingleEvent(of: .value, with: { snapshot in

        let user = UserClass(snap: snapshot)

        //this code is just to show the UserClass was populated.
        print(user.email)
        print(user.username)

        for group in user.groupsDict { //iterate over groups
            print(group)  //and print each one
        }

        print(user.loc.coords!) //print the location data
        print(user.loc.name!)
        print(user.loc.visibility!)
    })

The only remaining issue in your structure, theres a visibilityToSelectContacts node, which has a child node contacts.

So essentially the high level dictionary of userDict in the UserClass will have a child called visibilityToSelectContacts which then has a child contacts which has a child dictionary of key:value pairs of "gFTCpzgSJDOsrVKWbAJp0Z1JFXp1" : true. Like this

userDict
   visibilityToSelectContacts
      contacts
        contant_0: true
        contant_1: true

I will leave you to get that structure hammered out (hint: it's the same design pattern)

like image 192
Jay Avatar answered Oct 13 '22 12:10

Jay