如何解析firebase中的多个对象

时间:2017-07-30 01:57:12

标签: firebase swift3 firebase-realtime-database

我在Firebase中有一个数据库,如下所示: enter image description here

和两个对象:

class Area: NSObject {
let itemRef:FIRDatabaseReference?
var id:String?
var name:String?
var cities : [City] = []
var collapsed: Bool
}

class City: NSObject {
var id:String?
var name:String?
init(_ id:String,_ name: String) {
    self.id = id
    self.name = name
}

override init(){

}

这是我的解析代码:

func makeData(){
    let ref = FIRDatabase.database().reference().child("area")
    ref.observe(.childAdded, with: {
        (snapshot) in
        if let dictionary = snapshot.value as? [String:AnyObject]{
            print(dictionary)
        }
    })
}

我尝试将快照中的数据解析到我的阵列区域,但我不能 我怎么能这样做?

1 个答案:

答案 0 :(得分:2)

你需要这样的东西:

(这只是一个例子,你需要根据你的情况进行调整)

let ref = FIRDatabase.database().reference().child("area")

ref.observe(.childAdded, with: { (snapshot) in
    guard let dictionary = snapshot.value as? [String: Any] else {
        return
    }

    // Create the area object
    let area = Area()

    // Add id in the area
    area.id = snapshot.key

    // Init cities
    area.cities = [City]()

    if let cities = dictionary["cities"] as? [String: Any] {
        for (key, value) in cities {
            guard let cityName = value["name"] as? String else {
                continue
            }

            // Create the city object
            let city = City(key, cityName)

            // Add city to cities in the area
            area.cities.append(city)
        }
    }

    if let name = dictionary["name"] as? String {
        // Add name in the area
        area.name = name
    }

    // Use the area
})