我正在尝试从我从 Reddit 中提取的 JSON 对象中提取一些数据,并且在使用 SwiftyJSON 库时遇到问题(您可以在此处找到:https ://github.com/SwiftyJSON/SwiftyJSON )。
我在以下 URL 调用 Reddit 的 API,“ http://www.reddit.com/r/aww/hot.json ” 我试图从 json 响应中提取一些键值对,从作者开始一个列表。
我的代码如下:
import UIKit
class ViewController: UIViewController, NSURLConnectionDelegate {
var data = NSMutableData()
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.connectReddit()
}
func connectReddit() {
let urlPath: String = "http://www.reddit.com/r/aww/hot.json"
var url = NSURL(string: urlPath)!
var request = NSURLRequest(URL: url)
var connection = NSURLConnection(request: request, delegate: self, startImmediately: false)!
connection.start()
}
func connection(connection: NSURLConnection!, didReceiveData data: NSData!){
self.data.appendData(data)
}
func connectionDidFinishLoading(connection: NSURLConnection!) {
var err: NSError?
// throwing an error on the line below (can't figure out where the error message is)
let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
println(jsonResult)
let json = JSON(data: data)
let authorName = json["data"]["children"]["author"].stringValue
println(authorName)
}
}
您可以看到调用 SwifyJSON 类的代码,尝试解析它以获取数据如下,当我清楚地看到那里的数据时,我得到 nil 作为响应。
let json = JSON(data: data)
let authorName = json["data"]["children"]["author"].stringValue
println(authorName)
我不确定我在这里做错了什么。
谢谢您的帮助!