tectonicpie tectonicpie - 2 months ago 16
Swift Question

Swift Firebase Snapshot to object model

I am working with a large firebase database with at least 6 layers of hierarchy as well as many children for each node. I wanted to parse the entire snapshot and convert it into an object model. I found this solution but in my opinion it is extremely inefficient as parsing each node's children requries a call to firebase and this increases latency exponentially. Is there any way for the "ref.observeSingleEvent" to be done locally instead of making a call to firebase? Any other better alternatives would be much appreciated.

Answer Source
//this goes into your call (observeSingleEvent)
let enumerator = snapshot.children //assuming you use snapshot as name
    while let rest = enumerator.nextObject() as? FIRDataSnapshot {
       // this loops through every child in that map   
      let values = (rest as! DataSnapshot).value as? NSDictionary
      let coins= values?["coins"] as? Int ?? 0 
      //above code looks for a key with username and grabs the value from that. If it is not a string value it returns the default value.
      //use above code for picture 1
      if (rest as! DataSnapshot).key == "slot"{
        let enumeratorMap1 = (rest as! DataSnapshot).children
        while let rest2 = enumeratorMap1.nextObject() as? FIRDataSnapshot { 
         let valuesMap1 = (rest2 as! DataSnapshot).value as? NSDictionary
         //loop through values in new map
        //use this methodes for looping through maps, as stated in picture 2
         //keep repeating this method for any child under the map
          }
       }
    }

Picture 1: enter image description here

Picture 2: enter image description here