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!
To help us safely decode an Array we will need to create a structure called Throwable . It will handle the failed items without failing all our Array . The Throwable is a generic structure that implements the protocol Decodable .
An object that converts between JSON and the equivalent Foundation objects.
Swift JSON ParsingJSON stands for JavaScript Object Notation. It's a popular text-based data format used everywhere for representing structured data. Almost every programming language supports it with Swift being no exception. You are going to use JSON a lot throughout your career, so make sure you don't miss out.
Info is an array, so check with:
var name: String? = info[0].valueForKey("trackName") as? String
var name: String? = info[0].valueForKey("trackName") as? NSString
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With