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 (Retired) Concurrency Using Our JSON Data

Sebastian Röder
Sebastian Röder
13,878 Points

Which types of errors will be catched by `error == nil`?

In the video it is shown that our app crashes when we use an invalid URL. This is the reason why we added the if error == nil statement in the following code snippet:

let downloadTask = sharedSession.downloadTaskWithURL(forecastURL, completionHandler:
            { (location: NSURL!, response: NSURLResponse!, error: NSError!) -> Void in
                // TODO: Check that status code in NSHTTPURLResponse is 200 / OK
                // error will be nil even with status code 404 etc.
                if error == nil {
                    let forecastData = NSData(contentsOfURL: location)
                    let forecastJSON = NSJSONSerialization.JSONObjectWithData(forecastData, options: nil, error: nil) as NSDictionary
                }

However, as it turns out, this code still crashes when our URL is invalid. When the status code in the response is 404, the error is still nil, so the code inside the ifblock gets executed. Since forecastData is also nil, we get fatal error: unexpectedly found nil while unwrapping an Optional value in the next line.

So our error handling does not actually address the problem we wanted to solve. How can this be improved?

I wanted to check for response.statusCode == 200 in the if-statement but had a problem with NSHTTPResponse vs. NSHTTPURLResponse.

Sebastian Röder
Sebastian Röder
13,878 Points

OK, I found a solution by down casting NSURLResponse to NSHTTPURLResponse. My code looks like this now:

let downloadTask = sharedSession.downloadTaskWithURL(forecastURL, completionHandler:
    { (location: NSURL!, response: NSURLResponse!, error: NSError!) -> Void in

        let statusCode = (response as NSHTTPURLResponse).statusCode

        if error == nil && statusCode == 200 {
            let forecastData = NSData(contentsOfURL: location)
            let forecastJSON = NSJSONSerialization.JSONObjectWithData(forecastData,
                options: nil, error: nil) as NSDictionary
        }
})

1 Answer

Sebastian Röder is absolutely right, we can even remove the (error == nil) condition by using statusCode he provide instead, without problem, thanks for the answer!

Regards,