Daniel Jones
Daniel Jones

Reputation: 171

Storing an array in a Firebase Database

I am trying to store an array in the Firebase Database, but I'm not sure how to do it properly.

I am wanting to store an array such as:

var exampleArray = ["item1", "item2", "item3"]

The reason why is I populate a UIPicker with values from an array, and rather than having to push an update to the app each time to add a new value, it would be better if I could just update the database and instantly add the new value to each app.

Is there any way that I could store the values in the database and pull the values from the database and store it into an array as shown above?

Thank you.

Upvotes: 1

Views: 6362

Answers (2)

Chris Edgington
Chris Edgington

Reputation: 3236

The Firebase setValue method will accept an array just the same as a String or Integer. So you can read and write the values in the same way -

var ref: DatabaseReference!

ref = Database.database().reference()

var exampleArray = ["item1", "item2", "item3"]

// Write the array 
ref.child("myArray").setValue(exampleArray)

// Read the array 
ref.child("myArray").observe(.value) { snapshot in
  for child in snapshot.children {
    // Add the values to your picker array here
  }
}

Upvotes: 3

Dhruv Murarka
Dhruv Murarka

Reputation: 386

A simple solution would be read JSON from a Firebase Database Reference containing the array, and deserealize it in swift to a native swift array. See point 2 at https://firebase.google.com/docs/database/#implementation_path

Upvotes: 0

Related Questions