how parsing Firebase FDatasnapshot json data in swift

Viewed 10641

I'm having issue getting data from Firebase.

schema is

{
    title: "dog",
    images: {
        main: "dog.png",
        others: {
            0: "1.png",
            1: "2.png",
            2: "3.png"
        }
    }
}

how can i parse FDataSnapshot to swift model??

5 Answers

Try to play with this:

func makeItems(from snapshot: DataSnapshot) -> [SimpleItem] {
        var items = [SimpleItem]()
        if let snapshots = snapshot.children.allObjects as? [DataSnapshot] {
            for snap in snapshots {
                if let postDictionary = snap.value as? Dictionary<String, AnyObject> {
                    let item = SimpleItem(parentKey: snap.key, dictionary: postDictionary)
                    items.append(item)
                }
            }
        }
    return items
}

func loadItems() {
    firebaseService.databaseReference
        .child("items")
        .queryOrdered(byChild: "date")
        .queryLimited(toLast: 5)
        .observeSingleEvent(of: .value) { snapshot in
            let items = self.makeItems(from: snapshot)
            print(" \(items)")
    }
}

class SimpleItem {
    var parentKey: String?

    var id: String?
    var description: String?

    init(parentKey: String, dictionary: [String : AnyObject]) {
        self.parentKey = parentKey

        id = dictionary["id"] as? String
        description = dictionary["description"] as? String
    }
}

This will parse all the snapshot children in the single object and convert it in array and you can easily parse the array of children with index

if let snap = snapshot.children.allObjects as? [DataSnapshot]{
    print(snap)

    for (index,val) in snap.enumerated(){
        print("values")
        print(val)
        print(val.value)

    }
}
Related