0

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

3
  • Whats is error here? Commented Nov 16, 2016 at 5:02
  • Please don't store array's in Firebase. You cannot access specific elements. The entire array has to be read in to get the elements or completely replaced if you add or change something in the array. Also, you cannot insert. Array's should be avoided at all costs. Commented Nov 16, 2016 at 19:19
  • ah, so it wouldn't be an array of dictionaries? Commented Nov 16, 2016 at 21:59

2 Answers 2

2

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 :)

Sign up to request clarification or add additional context in comments.

Comments

1

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

6 Comments

Hi, sorry if this is delayed comment. I have been trying to solve the same issue. However once you denormalise the data, how do you get the details of that reference. So from your example -Y9jkoma9kmmsd: true. How would I get it's itemName and itemPrice.
@Chace You would observeSingleEvent on the node you want to read, since you know it's key. In latter part of my example, I suggest keeping the items in a separate node with a reference to them. So the items node would be Items/item_0/child nodes, and Items/Item_1/child nodes. Once you know the key of the item (Ymnk0s0s0k98s for example), just observe /Items/Ymnk0s0s0k98s which would retrieve that item and all of it's children (itemName, itemPrice etc)
Thanks I'll give it a go and if I am still unsure then I'll post a new question around that.
Would you be able to create the Dictionary like you mentioned that you could do above please.
@Chace I certainly can. But, it should be the answer would be for a different question that's specific to your use case. Can you please post a question, include the code you have tried and the Firebase structure you are using (as TEXT, please, no images or links) and I will take a look and write up an appropriate answer. Link it here,
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.