Lucas Crostarosa
Lucas Crostarosa

Reputation: 1192

Post Array to firebase Database in Swift

Question
I need to post data into the firebase database, which (in terms of arrays) can only accept type NSArray. The application however, needs to add to the array

Json Data that wil be posted

Object: someObjectKey[
  ArrayOfItems[
    Item: someItemNumber
    Item: someItemNumber
    Item: someItemNumber
  ]
  TimeStamp: 102047355
  SomeOtherTimeStamp: null
  SomeInt: 1111
  someOtherInt: 2222
  SomeBoolean: false
  ]
}

Goal
How can I get the data above to be pushed up into the database?

Attempted Avenues
-Convert a SwiftArray to a NSArray
-Convert an NSMutableArray to a NSArray

Code

public func postToFireBase(){

    var Timestamp: String {
        return "\(NSDate().timeIntervalSince1970 * 1000)"
    }

    var someInt = 1111
    var someOtherInt = 2222
    let myArrayOfStuff = convertItemsToNSArray()

    let post: [String : Any] = ["timestamp": Timestamp,
                "someInt": someInt,
                "someOtherInt": someOtherInt,
                "items": ItemList]

    //Method Call References the FIRDatabase.database.reference.child...
    FirebaseDatabaseService.databaseReference.setValue(post)
}

private func convertItemsToNSArray() -> NSArray{
    var thisArray: NSMutableArray = []

    for item in items{
        thisArray.add(["name": "Foo",
                       "key": "Bar",
                       "someCoolInt": 1234])
    }
    return thisArray
    //This won't work because it's coming back as NSMutableArray anyway
}

Cheers

Upvotes: 0

Views: 3096

Answers (2)

Jay
Jay

Reputation: 35648

Your Firebase structure should look like this

-Yk8hsinuoioas90kp
  TimeStamp: 102047355
  SomeOtherTimeStamp: null
  SomeInt: 1111
  someOtherInt: 2222
  SomeBoolean: false
  Items
    -Y9jkoma9kmmsd
       itemName: "The best item"
       itemPrice: "1.90"
    -Ymnk0s0s0k98s
       itemName: "Another great item"
       itemPrice: "9.99"
    -JYOjsomojkspy
       itemName: "The best item evah"
       itemPrice: "4.99"

To get that you simply create a dictionary and the parent nodes are created with childByAutoId. Then add the child nodes as key:value pairs, with the child node of Items also being a Dictionary of key:value pairs.

Finally write the dictionary with a

let thisThingRef = ref.childByAutoId()

thisThingRef.setValue(myDict)

I can craft up some code to create that Dictionary if you need it.

Oh... and you may want to denormalize the data a bit and have the Items stored in a separate node and just keep a reference to it

-Yk8hsinuoioas90kp
  TimeStamp: 102047355
  SomeOtherTimeStamp: null
  SomeInt: 1111
  someOtherInt: 2222
  SomeBoolean: false
  Items
    -Y9jkoma9kmmsd: true
    -Ymnk0s0s0k98s: true
    -JYOjsomojkspy: true

Upvotes: 1

Ccr
Ccr

Reputation: 686

I can't remember exactly whats the reason, but did faced similar problem too, in both android and Ios.workaround is that save the array by converting it to a dictionary first.

let's say I have array of longitude and latitude:

I first create a class for to wrap lat and long. I have a function to get the dictionary which wraps the required data.

class HiddenLatlng {
private var latitude: Double
private var longitude: Double

init(lat: Double, lng: Double) {
    self.latitude = lat
    self.longitude = lng
}

func toDictionery() -> [ String : Double ] {
    var dict = [ String : Double ]()
    dict["latitude"] = self.latitude
    dict["longitude"] = self.longitude
    return dict
}

}

just before saving the array to firebase, first convert this array to dictionary using above class.

       var dict = [String: AnyObject]() // main dictionary saved to firebase

       var dictArray = [ String : [String: Double] ]() // temp dictionary
        for (index, element) in hide.vertices.enumerate(){
            dictArray[String(index)] =  HiddenLatlng(lat: element.latitude, lng: element.longitude).toDictionery()
        }
        dict["eventLatLngList"] = dictArray // add temp dictionary to main dictionary.

`

now we can save it to firebase.

self.reference.child("yourKey").child(key).updateChildValues(dict) { (error: NSError?, reference: FIRDatabaseReference) in
            completion(error) // if some error handle it.
        }

I hope it saves you some time and trouble :)

Upvotes: 2

Related Questions