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 Build a Weather App with Swift Managing Complexity Methods with Closures

O Or
O Or
2,761 Points

Help with practice task

I tried tackling the practice question but I couldn't even get past the first task. Could some please share their solution and briefly explain what their code is doing? Thanks

2 Answers

Richard Lu
Richard Lu
20,185 Points

Hi O,

I'm assuming that the question you are asking is about creating a method named fetchTreehouseBlogPosts. The first part of the challenge wants you to create a function with a single parameter that is a function type of NSData!, NSURLResponse!, NSError! and returns Void. You have the option of assigning it to a typealias named BlogPostCompletion.

typealias BlogPostCompletion = ((NSData!, NSURLResponse!, NSError!) -> Void)    // outer parenthesis are required and may be a bug in this problem 

func fetchTreehouseBlogPosts(completion: BlogPostCompletion) { }

The second part of this challenge is to create a data task (not a download task), named dataTask, with a completion handler that returns the results of the data task. In order to do that, we need a NSURLSession which is provided

typealias BlogPostCompletion = ((NSData!, NSURLResponse!, NSError!) -> Void)    // outer parenthesis are required and may be a bug in this problem 

func fetchTreehouseBlogPosts(completion: BlogPostCompletion) {
   // snippet of code provided 
   let blogURL = NSURL(string: "http://blog.teamtreehouse.com/api/")
   let requestURL = NSURL(string: "get_recent_summary/?count=20", relativeToURL: blogURL)

   let request = NSURLRequest(URL: requestURL!)

   let config = NSURLSessionConfiguration.defaultSessionConfiguration()
   let session = NSURLSession(configuration: config)
}

Now for the creation of the dataTask:

let dataTask = session.dataTaskWithRequest(request) {
   (let data, let response, let error) in    // these are the result values from the data task
   completion(data, response, error)   // use the result values to 'complete' the dataTask
}

// calling the dataTask
dataTask.resume()

When the code is put together, this will be your result:

typealias BlogPostCompletion = ((NSData!, NSURLResponse!, NSError!) -> Void)    
func fetchTreehouseBlogPosts(completion: BlogPostCompletion) {
   // snippet of code provided 
   let blogURL = NSURL(string: "http://blog.teamtreehouse.com/api/")
   let requestURL = NSURL(string: "get_recent_summary/?count=20", relativeToURL: blogURL)

   let request = NSURLRequest(URL: requestURL!)

   let config = NSURLSessionConfiguration.defaultSessionConfiguration()
   let session = NSURLSession(configuration: config)

   let dataTask = session.dataTaskWithRequest(request) {
      (let data, let response, let error) in    // these are the result values from the data task
      completion(data, response, error)   // use the result values to 'complete' the dataTask
   }

   // calling the dataTask
   dataTask.resume()
}

Hope this helps! Happy Coding! :)

O Or
O Or
2,761 Points

Oh for sure, I'm a lot happier. Thanks for the very detailed explanation!

Richard Lu Hi, can you explain to me what is the meaning of completion(data, response, error) What do you mean to 'complete' the dataTask?

Christian Dangaard
Christian Dangaard
3,378 Points

Thank you Richard, this helped a lot. I've gone through and rewatched Closures as a recap but could not get the answer correctly. Gotta put ego aside, but by looking at your answer it's helped me further understand this subject,

Richard Lu
Richard Lu
20,185 Points

Hi Christian Dangaard ,

I'm glad to hear that you benefited through this post. I really brings me joy when I find out that I've helped someone.

Happy Coding! :)

Tal Zion
Tal Zion
6,234 Points

Hi,

Not sure if you found a solution, but I found that the video is outdated. Swift 2.0 introduced do, try, catch, throw euro handling. When using the NSJSONSerialization.JSONObjectWithData, the compiler expects a Swift 2.0 implementation of error handling. Thus, this is how you code should look like:

    func downloadJSONFromURL(completion: JSONDictionaryComplition){

        //let request:NSURLRequest = NSURLRequest(URL: queryURL)
        let dataTask = session.dataTaskWithURL(queryURL){
            (let data, let response, let error) in
            //1. Checl HTTP response for succesful GET request
            do {
            if let httpResponse = response as? NSHTTPURLResponse {
                switch(httpResponse.statusCode){
                case 200:
                    //2. Create JSON object with data
                    let jsonDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [String:AnyObject]
                default:
                    print("GET request not successful. HTTP status code: \(httpResponse)")
                }
            }
            }catch{
                print("ERROR: Error...")
            }
        }
        dataTask.resume()
    }