Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

JSON dictionary returns nil of 'posts' key

I am trying to use the JSON framework from the stormy project to fetch data from my schools blog. Every time I build and run the app I get the readout "JSON dictionary returns nil of 'posts' key."

The blog URL I am using is http://www.chsd117.org/index.php/app/state-of-lakes

DataService.swift

struct DataService {

func getForecast(completion: (BlogPosts? -> Void)) {
    if let blogURL = NSURL(string: "http://www.chsd117.org/index.php/app/state-of-lakes") {

        let networkOperation = NetworkOperation(url:blogURL)

        networkOperation.downloadJSONFromURL {
            (let JSONDictionary) in
            let blogPosts = self.blogPostsFromJSON(JSONDictionary)
            completion(blogPosts)
        }

    }else{
        println("Could not contruct a valid URL")
    }
}




func blogPostsFromJSON(jsonDictionary: [String: AnyObject]?) -> BlogPosts? {
    if let currentPostDictionary = jsonDictionary?["posts"] as? [String: AnyObject] {
        return BlogPosts(postDictionary: currentPostDictionary)
    } else {
        println("JSON dictonary returned nil of 'posts' key")
        return nil
    }
}

}

NetworkOperation.swift

class NetworkOperation {

lazy var config: NSURLSessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration()
lazy var session: NSURLSession = NSURLSession(configuration: self.config)
let queryURL: NSURL

typealias JSONDictionaryCompletion = ([String: AnyObject]?) -> Void

init(url: NSURL) {
    self.queryURL = url
}



func downloadJSONFromURL(completion: JSONDictionaryCompletion) {

    let request: NSURLRequest = NSURLRequest(URL: queryURL)
    let dataTask = session.dataTaskWithRequest(request) {
        (let data, let response, let error) in

        // 1. Check HTTP response for successful GET request


        if let httpResponse = response as? NSHTTPURLResponse {
            switch(httpResponse.statusCode) {
            case 200:
                // 2. Create JSON object with data
                let jsonDictionary =
                NSJSONSerialization.JSONObjectWithData(data, options: nil,
                    error: nil) as? [String: AnyObject]
                completion(jsonDictionary)
            default:
                println("GET request not successful. HTTP status code: \(httpResponse.statusCode)")
            }
        } else {
            println("Error: Not a valid HTTP response")
        }

    }

    dataTask.resume()
}

}

BlogPost.swift

struct BlogPosts {

var title: String?
var author: String?
var thumbnail: String?
var date: String?
var url: NSURL = NSURL()

init(postDictionary: [String: AnyObject]) {
title = postDictionary["title"] as? String
//author = postDictionary["author"] as? String
thumbnail = postDictionary["blog_photo"] as? String
date = postDictionary["entry_date"] as? String
}



func thumbnailURL() -> NSURL {
    return NSURL(string:thumbnail!)!
}

func formattedDate() -> String {
    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
    let tempDate = dateFormatter.dateFromString(date!)
    dateFormatter.dateFormat = "EE MMM, dd"
    return dateFormatter.stringFromDate(tempDate!)
    }

}