7

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!

1 Answer 1

17

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
Sign up to request clarification or add additional context in comments.

1 Comment

Awesome! It worked! Why do I need to specify the index, "0"? In Objective-C I could use a way similar to what I have and it would spit out a string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.