在Swift中从JSON数组中获取值 [英] Getting Values from JSON Array in Swift
问题描述
我正在尝试从JSON Web请求中获取的数组中检索值。但我无法使valueForKey函数工作,所以我可以将String应用于标签。以下示例在Apples API中搜索软件。作为测试,我希望能够将trackName键应用于UILabel,但我尝试的一切,我要么崩溃,要么返回nil。
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.
这是我的代码
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)转换为可以应用于标签的字符串吗?
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?
谢谢!
推荐答案
信息是一个数组,请查看:
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
这篇关于在Swift中从JSON数组中获取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!