Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Values from JSON Array in Swift

Tags:

ios

swift

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!

like image 403
DookieMan Avatar asked Jun 06 '14 04:06

DookieMan


People also ask

How do you decode an array of objects in Swift?

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 .

What is Jsonserialization in Swift?

An object that converts between JSON and the equivalent Foundation objects.

What is JSON parsing in Swift?

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.


1 Answers

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
like image 53
Midhun MP Avatar answered Nov 06 '22 11:11

Midhun MP