如何在swift中解析Firebase FDatasnapshot json数据

时间:2022-02-02 20:04:41

I'm having issue getting data from Firebase.

我在从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??

我如何解析FDataSnapshot快速模型?

4 个解决方案

#1


3  

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

Firebase是NoSQL JSON数据库,没有架构,也没有表。数据以带有节点的“树”结构存储;父母和孩子。

You don't need to parse Firebase JSON data to access it, you can access it directly.

您无需解析Firebase JSON数据来访问它,您可以直接访问它。

FDataSnapshots contain a .key, which is it's parent key in Firebase and .value. .Value may contain one node, or multiple nodes. The Value will have key:value pairs representing the data within the snapshot

FDataSnapshots包含一个.key,它是Firebase和.value中的父键。 .Value可能包含一个节点或多个节点。 Value将具有表示快照中数据的键:值对

So for your example you will have a Firebase structure like this

因此,对于您的示例,您将拥有这样的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"

So, say you want to read in each dog_id_x node one at a time and print some values.

所以,假设您想要一次读取每个dog_id_x节点并打印一些值。

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"))
})

This will output

这将输出

dog
Alaskan Malamute
another dog
Boxer

The dog_id_0 and dog_id_1 are node names created with the Firebase childByAutoId.

dog_id_0和dog_id_1是使用Firebase childByAutoId创建的节点名称。

You could just as easily create a Dog class, and pass it the FDataSnapshot which will populate the class from the data within the snapshot.

你可以轻松地创建一个Dog类,并将它传递给FDataSnapshot,它将从快照中的数据填充该类。

#2


1  

February 2017 Update, Swift 3 Xcode 8

2017年2月更新,Swift 3 Xcode 8

Since a lot of things with Swift3 and Firebase have changed by the time this question was asked I will provide an updated way to parse Firebase data:

由于在提出此问题时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)
    }

#3


1  

You could parse it maually with Dictionary or you can use my library.

您可以使用Dictionary手动解析它,也可以使用我的库。

Example code for your case:

您案例的示例代码:

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

#4


1  

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

#1


3  

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

Firebase是NoSQL JSON数据库,没有架构,也没有表。数据以带有节点的“树”结构存储;父母和孩子。

You don't need to parse Firebase JSON data to access it, you can access it directly.

您无需解析Firebase JSON数据来访问它,您可以直接访问它。

FDataSnapshots contain a .key, which is it's parent key in Firebase and .value. .Value may contain one node, or multiple nodes. The Value will have key:value pairs representing the data within the snapshot

FDataSnapshots包含一个.key,它是Firebase和.value中的父键。 .Value可能包含一个节点或多个节点。 Value将具有表示快照中数据的键:值对

So for your example you will have a Firebase structure like this

因此,对于您的示例,您将拥有这样的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"

So, say you want to read in each dog_id_x node one at a time and print some values.

所以,假设您想要一次读取每个dog_id_x节点并打印一些值。

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"))
})

This will output

这将输出

dog
Alaskan Malamute
another dog
Boxer

The dog_id_0 and dog_id_1 are node names created with the Firebase childByAutoId.

dog_id_0和dog_id_1是使用Firebase childByAutoId创建的节点名称。

You could just as easily create a Dog class, and pass it the FDataSnapshot which will populate the class from the data within the snapshot.

你可以轻松地创建一个Dog类,并将它传递给FDataSnapshot,它将从快照中的数据填充该类。

#2


1  

February 2017 Update, Swift 3 Xcode 8

2017年2月更新,Swift 3 Xcode 8

Since a lot of things with Swift3 and Firebase have changed by the time this question was asked I will provide an updated way to parse Firebase data:

由于在提出此问题时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)
    }

#3


1  

You could parse it maually with Dictionary or you can use my library.

您可以使用Dictionary手动解析它,也可以使用我的库。

Example code for your case:

您案例的示例代码:

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

#4


1  

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