我有JSON数据进入我的swift应用程序。我想创建一个查询,但我的数组返回为零。以下是我的代码:
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.
}
}
为什么查询不起作用。欢迎所有建议。
答案 0 :(得分:1)
正如larme的建议使用以下更改纠正您的代码。
let results: NSDictionary = jsonresult["results"] as NSDictionary
let collection1: NSArray = results["collection1"] as NSArray
println(collection1)
for item in collection1 {
var quote:String = item["quote"] as String
println("\(quote)")
}