在Swift中从JSON数组中获取值

时间:2022-10-10 21:16:34

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.

我正在尝试从JSON Web请求中获取的数组中检索值。但我无法使valueForKey函数工作,所以我可以将String应用于标签。以下示例在Apples API中搜索软件。作为测试,我希望能够将“trackName”键应用于UILabel,但我尝试的一切,我要么崩溃,要么返回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?

变量旁边的注释解释了每个变量会发生什么。有人可以解释我如何将valueForKey(“trackName”)转换为可以应用于标签的字符串吗?

Thank you!

谢谢!

1 个解决方案

#1


17  

Info is an array, so check with:

Info是一个数组,请查看:

var name: String? = info[0].valueForKey("trackName") as? String
var name: String? = info[0].valueForKey("trackName") as? NSString

#1


17  

Info is an array, so check with:

Info是一个数组,请查看:

var name: String? = info[0].valueForKey("trackName") as? String
var name: String? = info[0].valueForKey("trackName") as? NSString