0

i have a database in Firebase look like: enter image description here

and two objects:

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

and

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

override init(){

}

and this is my parsing code :

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

I try to parse the data in snapshot to my array Area but i cannot how i can do it?

1
  • 1
    You code refers to a child arena, but your JSON doesn't show such a child. Please replace the screenshot of the JSON with the actual text of the JSON and include the node that is referenced in the code. You can get the JSON as text by clicking the "Export JSON" link in your Firebase Database console. Commented Jul 30, 2017 at 2:01

1 Answer 1

2

You need something like that :

(It's just an example, you need to adapt this for your case)

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
})
Sign up to request clarification or add additional context in comments.

3 Comments

Thank for your answer but error in this line let city = City(key, value as! String) with error Could not cast value of type '__NSDictionaryM' (0x101ffd2b0) to 'NSString' (0x103280c60).
Try City(key, value["name"] as! String)
it's work perfect, thank you very much, you are my hero. but i have to change [String: Any] to [Strinng:AnyObjects]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.