【发布时间】:2015-01-13 05:53:09
【问题描述】:
我的 swift 应用程序中有 JSON 数据。我想创建一个查询,但数组返回为零。下面是我的代码:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var RandomQuoteLabel: UITextField!
var bytes: NSMutableData?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let request = NSURLRequest(URL: NSURL(string: "https://www.kimonolabs.com/api/1vldybe0?apikey=iFotcJDm95fB6Ua7XiZRDZA0jl3uYWuc")!)
let loader = NSURLConnection(request: request, delegate: self, startImmediately: true)
}
func connection(connection: NSURLConnection!, didReceiveData conData: NSData!) {
self.bytes?.appendData(conData)
}
func connection(didReceiveResponse: NSURLConnection!, didReceiveResponse response: NSURLResponse!) {
self.bytes = NSMutableData()
}
func connectionDidFinishLoading(connection: NSURLConnection!) {
let jsonresult:NSDictionary = NSJSONSerialization.JSONObjectWithData(self.bytes!, options: nil, error: nil) as NSDictionary
println(jsonresult)
//This is where the app crashes
let results: NSArray = jsonresult["collection1"] as NSArray
println(results)
for item in results {
var quote:String = item["quote"] as String
println("\(quote)")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
为什么查询不起作用。欢迎所有建议。
【问题讨论】:
-
collection1是jsonresult["results"]的对象,而不是来自jsonresult的“直接”对象,您缺少一个级别 =>let results: NSArray = jsonresult["results"] as NSDictionary和let collection1: NSArray = results["collection1"] as NSArray -
它说 NSDictionary 不能转换为 NSArray。
-
对不起,我搞砸了复制/粘贴。
let results: NSDictionary = ...关键是你错过了一个关卡。 -
好的,谢谢。我虽然是这样。 :) 我怎样才能投票给你。
标签: ios json xcode parsing swift