简体   繁体   中英

Retrieve array of dictionary from Firebase & Swift 3

I have a json database on firebase and trying to get them and put into local array of dictionaries.

My json model on Firebase

在此输入图像描述

My struct model is also like below

struct Places {
var type:String!
var country:String!
var name:String!
var image:String!
var coords:[Coords]!


init(type: String, country: String, name: String, image: String, coords: [Coords]) {
    self.type = type
    self.country = country
    self.name = name
    self.image = image
    self.coords = coords
}

init(snapshot: FIRDataSnapshot) {

    let snapshotValue = snapshot.value as! [String:Any]

    type = snapshotValue["type"] as! String
    country = snapshotValue["country"] as! String
    name = snapshotValue["name"] as! String
    image = snapshotValue["image"] as! String
    coords = snapshotValue["coords"] as! [Coords]!
}

}

And also [Coords] struct model like below:

struct Coords {

var latStart:String!
var latEnd:String!
var lonStart:String!
var lonEnd:String!

init(latStart: String, latEnd: String, lonStart: String, lonEnd: String) {
    self.latStart = latStart
    self.latEnd = latEnd
    self.lonStart = lonStart
    self.lonEnd = lonEnd
}

}

And I am trying to get and put json data by below code:

placesRef.observeSingleEvent(of: .value, with: { (snapshot) in

            if !snapshot.exists() {
                print("data not exist")
                return
            }

                var plc: [Places] = []

                for eachPlace in (snapshot.children){
                    let place = Places(snapshot: eachPlace as! FIRDataSnapshot)

                    plc.append(place)
                }

            self.allPlaces = plc

The problem is that I can get the array of dictionary except coords dictionary inside array of dictionary. [Coords] dictionary seems null and I would like to know what the problem is. Thanks for any suggestion.

Because snapshotValue["coords"] as! [Coords]! snapshotValue["coords"] as! [Coords]! are not Coords yet. They are just dictionaries. You have to go through each dictionary in snapshotValue[“coords”] and init a Coords object, then when you're finished group them all into an array and assign it to self.coords of the Places struct. The map function is really convenient for this.

Example:

I would change the Coords init function to something like:

init(dictionary: [String : AnyObject]) {
    self.latStart = dictionary["lat1"] as? String
    //...
    //...
}

Then in Places init use something like:

coords = (snapshotValue["coords"] as? [[String : AnyObject]])?.map({ Coord(dictionary: $0) })

I didn't test this and making some assumptions here, but you should be able to make something similar work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM