Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Paul Yorde
10,497 PointsHow to retrieve value of array element which is inside of a dictionary, in swift?
I was able to get a movie selection from Rotten Tomatoes, however, the JSON returned has an array inside of a dictionary, which I'm not familiar with. I have tried this, but it returns nil:
println(moviesDictionary["movies"]?.title)
The Code:
class ViewController: UIViewController {
private let apiKey = "notGonnaTellYa"
override func viewDidLoad() {
super.viewDidLoad()
let baseURL = NSURL(string: "http://api.rottentomatoes.com/api/public/v1.0/lists/movies/")
let inTheatersURL = NSURL(string: "in_theaters.json?apikey=\(apiKey)", relativeToURL: baseURL)
let sharedSession = NSURLSession.sharedSession()
let downloadTask: NSURLSessionDownloadTask = sharedSession.downloadTaskWithURL(inTheatersURL!, completionHandler: { (location: NSURL!, response: NSURLResponse!, error: NSError!) -> Void in
if (error == nil) {
let dataObject = NSData(contentsOfURL: location)
let moviesDictionary: NSDictionary = NSJSONSerialization.JSONObjectWithData(dataObject!, options: nil, error: nil) as NSDictionary
println(moviesDictionary["movies"]?.title)
}
})
downloadTask.resume()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
1 Answer
Andres Oliva
7,810 PointsTry saving moviesDictionary["movies"] in an array, an then access it as you're used to.