Dan Riaz - 9 months ago 77
iOS Question

SwiftyJSON Problems

I am trying to extract some data out of a JSON object I am pulling in from Reddit, and am having issues when using the SwiftyJSON library (you can find this here: https://github.com/SwiftyJSON/SwiftyJSON).

I am calling Reddit's API at the following URL, "http://www.reddit.com/r/aww/hot.json" I am trying to extract a few key value pairs out of the json response, starting with the author of a listing.

My code is below:

import UIKit

class ViewController: UIViewController, NSURLConnectionDelegate {

var data = NSMutableData()

}

// 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)
}

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)
}

}


You can see the code calling the SwifyJSON class, trying to parse it for data is the following, I am getting nil as a response when I clearly see data there.

let json = JSON(data: data)
let authorName = json["data"]["children"]["author"].stringValue
println(authorName)


I am not sure what I am doing wrong here.

Thanks for the help!

let authorName = json["data"]["children"][0]["data"]["author"].stringValue