anon
anon

Reputation:

Accessing Nested NSDictionary values in Swift 3.0

I have the following data I received from Firebase. I have made my snapshotValue a NSDictionary.

enter image description here

self.ref.child("users").child(facebookID_Firebase as! String).observeSingleEvent(of: .value, with: { (snapshot) in
            let snapshotValue = snapshot.value as? NSDictionary
            print(snapshotValue, "snapshotValue")
            //this line of code doesn't work
            //self.pictureURL = snapshot["picture"]["data"]["url"]
        }) { (error) in
            print(error.localizedDescription)
        }

I tried How do I manipulate nested dictionaries in Swift, e.g. JSON data? , How to access deeply nested dictionaries in Swift , and other solutions yet no luck.

How do I access the url value inside the data key AND the picture key?

I can make another reference in Firebase and get the value, but I'm trying to save another request. 😓

Upvotes: 1

Views: 1996

Answers (4)

Gonzalo Durañona
Gonzalo Durañona

Reputation: 57

You can use the following syntax, that is prettier:

    if let pictureDict = snapshot.value["picture"] as? [String:AnyObject],
        let dataDict = pictureDict.value["data"] as? [String:AnyObject] {
            self.pictureURL =  dataDict.value["url"] as! String
        }
    }

Upvotes: 0

Eugene Brusov
Eugene Brusov

Reputation: 17846

Inline dictionary unwrapping:

let url = ((snapshot.value as? NSDictionary)?["picture"] as? NSDictionary)?["url"] as? String

Upvotes: 0

Dravidian
Dravidian

Reputation: 9945

Try using :-

 if let pictureDict = snapshot.value["picture"] as? [String:AnyObject]{

        if let dataDict = pictureDict.value["data"] as? [String:AnyObject]{

              self.pictureURL =  dataDict.value["url"] as! String

           }
   }

Upvotes: 1

Cemal Eker
Cemal Eker

Reputation: 1266

When you refrence to a key of a Dictionary in swift you get out an unwrapped value. This means it can be nil. You can force unwrap the value or you can use pretty if let =

this should probably work.

if let pictureUrl = snapshot["picture"]["data"]["url"] {
    self.pictureURL = pictureUrl
}

Upvotes: 2

Related Questions