1

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.

Community
  • 1
  • 1
Rohit Tigga
  • 2,373
  • 9
  • 43
  • 81

4 Answers4

2

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
}
Cemal Eker
  • 1,266
  • 1
  • 9
  • 24
1

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

           }
   }
Dravidian
  • 9,945
  • 3
  • 34
  • 74
0

Inline dictionary unwrapping:

let url = ((snapshot.value as? NSDictionary)?["picture"] as? NSDictionary)?["url"] as? String
Eugene Brusov
  • 17,146
  • 6
  • 52
  • 68
0

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