在Swift中从JSON数组中获取值

时间:2014-06-06 04:12:36

标签: ios swift

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

这是我的代码

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")

}

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

谢谢!

1 个答案:

答案 0 :(得分:17)

Info是一个数组,请查看:

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