How to parse Firebase FDatasnapshot json data in swift

I have a problem getting data from Firebase.

scheme

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

How can I parse FDataSnapshot for a fast model?

+4
source share
4 answers

Firebase is a NoSQL JSON database and has no schema and tables. Data is stored with a tree structure with nodes; parents and children.

You do not need to analyze Firebase JSON data to access it, you can access it directly.

FDataSnapshots contains the key .key, which is the parent key in Firebase and .value..Value can contain one node or several nodes. The value will have key: value pairs representing the data in the snapshot

, Firebase,

dogs
  dog_id_0
    title: "dog"
    type: "Alaskan Malamute"
    images:
        main: "dog.png"
        others:
            0: "1.png"
            1: "2.png"
  dog_id_1
    title: "another dog"
    type: "Boxer"
    images:
        main: "another_dog.png"
        others:
            0: "3.png"
            1: "4.png"

, , dog_id_x node .

var ref = Firebase(url:"https://your-app.firebaseio.com/dogs")

ref.observeEventType(.ChildAdded, withBlock: { snapshot in
    println(snapshot.value.objectForKey("title"))
    println(snapshot.value.objectForKey("type"))
})

dog
Alaskan Malamute
another dog
Boxer

Dog_id_0 dog_id_1 - node, FirebaseByAutoId.

Dog FDataSnapshot, .

+3

2017 , Swift 3 Xcode 8

Swift3 Firebase , , Firebase:

    let userID = FIRAuth.auth()?.currentUser?.uid

    //I am registering to listen to a specific answer to appear
    self.ref.child("queryResponse").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
        //in my case the answer is of type array so I can cast it like this, should also work with NSDictionary or NSNumber
        if let snapshotValue = snapshot.value as? NSArray{
            //then I iterate over the values
            for snapDict in snapshotValue{
                //and I cast the objects to swift Dictionaries
                let dict = snapDict as! Dictionary<String, Any>
            }
        }
    }) { (error) in
        print(error.localizedDescription)
    }
+1

Dictionary, .

:

func main(){
    let root=SnapshotParser().parse(snap: Snapshot, type: Root.self)
}

class Root: ParsableObject {
    var title:String?=nil
    var images:Images?=nil

    required init(){}

    func bindProperties(binder: SnapshotParser.Binder) {
        binder.bindField(name: "title", field: &title)
        binder.bindObject(name: "images", field: &images)
    }
}

class Images: ParsableObject {
    var main:String?=nil
    var others:[Int:String]?=nil

    required init(){}

    func bindProperties(binder: SnapshotParser.Binder) {
        binder.bindField(name: "main", field: &main)
        binder.bindDictionary(name: "others", dict: &others)
    }
}
+1

:

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
    }
}
0

All Articles