Markus Johansson Markus Johansson - 3 months ago 74x
Swift Question

Save array of classes into Firebase database using Swift

I have an array of classes, which looks like this:

var myItems = [myClass]()

class myClass: NSObject {

var a: String?

var b: String?

var c: String?

var d: String?


What I want is to save the array called myItems into my database, and have every class inside of a personal section inside the database. Basically, I want every class to look like the one called "Eko" in this image: enter image description here

To clarify, after "Eko" all the rest of the classes which is inside of the array myItems should be displayed. To achieve what the picture is demonstrating, I used this code:

let data = self.myItems[0]

let currU = FIRAuth.auth()?.currentUser?.uid
let userRef = self.ref.child("users").child(currU!).child(data.a!)
userRef.updateChildValues(["a": data.a!, "b": data.b!, "c": data.c!, "d": data.d!])

Obviously, this will only save the class at index 0 from the array myItems into the Firebase Database, which is displayed in the image above. My question is thus, how do I save the entire array into the database? With my code I can only save 1 class from the array, and I would like to save all of the items into the database, so that they end up looking the same way that the one class does in the image. You could compare this to populating a tableView, where you need the "indexPath.row" to populate it with all the items instead of only one. I hope that I was clear enough!

Jay Jay

You can't save a class into Firebase. But.. A class has a similar structure to a dictionary (properties and values, like key: value pairs etc).

Arrays in Firebase should generally be avoided - they have limited functionality and the individual elements cannot be accessed and for any changes you have to re-write the entire array.

Using a structure where the parent key names are created with childByAutoId is usually preferred.

The easiest solution is to simply add intelligence to the class so it would craft a dictionary and then save itself.

Craft a user class

  var name = String()
  var food = String()

  func saveToFirebase() {
     let usersRef = myFirebase.child(users)
     let dict = ["name": self.myName, "food", self.myFood]

     let thisUserRef = usersRef.childByAutoId()

and and array to store them

var usersArray = [Users]()

populate the array

var aUser = UserClass() = "Leroy" = "Pizza"

var bUser = UserClass() = "Billy" = "Tacos"

and then iterate over the array saving each user

for user in usersArray {

this will result in

      name: Leroy
      food: Pizza
      name: Billy
      food: Tacos

which is very similar to the structure you want. There are many other ways of creating this structure. For example, you could craft the entire dictionary in code and write it all out at one time.

Pardon typo's, I wrote this on the fly.