在Swift中从JSON数组中获取值

编程入门 行业动态 更新时间:2024-10-05 17:22:47
本文介绍了在Swift中从JSON数组中获取值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试从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("itunes.apple/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数组中获取值

本文发布于:2023-11-26 23:13:27,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1635596.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组中   Swift   JSON

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!