I'm trying to retrieve values from an array that I get from a JSON web request. But I can't get the valueForKey function to work so I can apply the String to a label. The example below searches Apples API for software. As a test, I want to be able to apply the "trackName" key to a UILabel, but everything I try, I either crash, or return nil.
Here is my code
func searchFunction(searchQuery: NSString) {
var url : NSURL = NSURL.URLWithString("https://itunes.apple.com/search?term=\(searchQuery)&media=software")
var request: NSURLRequest = NSURLRequest(URL:url)
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config)
let task : NSURLSessionDataTask = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
var newdata : NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
var info : NSArray = newdata.valueForKey("results") as NSArray
var name: String? = info.valueForKey("trackName") as? String // Returns nil
println(name)//Returns nil
var name2 : NSString = info.valueForKey("trackName") as NSString //Crashes
println(name2) //Crashes
});
task.resume()
println("Resumed")
}
The comments next to the variables explains what happens with each one. Can someone explain how I can convert the valueForKey("trackName") to a string that can be applied to a label?
Thank you!