Dan Riaz Dan Riaz - 3 months ago 51
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()

override func viewDidLoad() {

override func didReceiveMemoryWarning() {
// Dispose of any resources that can be recreated.

override func viewWillAppear(animated: Bool) {

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

func connection(connection: NSURLConnection!, didReceiveData data: NSData!){

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

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


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

I am not sure what I am doing wrong here.

Thanks for the help!


you should try this ;

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