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 trialConor Quinn
3,461 PointsDownload task issue with unwrapping optional
Hi, unless I change the dataObject parameter in weather dictionary to an optional xcode gives me an error. However, when I run it like that the console returns "fatal error: unexpectedly found nil while unwrapping an Optional value"
Thanks!
Here is my code:
let downloadTask: NSURLSessionDownloadTask = sharedSession.downloadTaskWithURL(forecastURL!, completionHandler: { (location: NSURL!, response: NSURLResponse!, error: NSError!) -> Void in
if (error == nil) {
let dataObject = NSData(contentsOfURL: location)
let weatherDictionary: NSDictionary = NSJSONSerialization.JSONObjectWithData(dataObject!, options: nil, error: nil) as NSDictionary
println(weatherDictionary)
}
})
1 Answer
Unsubscribed User
11,496 PointsHi Conor,
That code looks good to me. The error you're getting suggests that you're not getting any data back from web service. When you use the "!" you're promising the swift compiler that the value you're unwrapping will not be "nil", so when it turns out that it is "nil", you get an error.
The most likely cause is a typo or error in one of the above lines where you're defining the baseURL or forecastURL. Make sure you're using the correct api key and that the map coordinates you're giving it are valid. You can test the URL outside of xcode by just copy-pasting it into your browser. If it's correct, you should get a screen full of weather data back.
Kyle Vogel
2,415 PointsIf we simulate an error with the URL on purpose, how can we fix the bang (!) operator unwrapping issue on forecastURL? How can we check to see if that's valid first?
Dave Faliskie
17,793 PointsDave Faliskie
17,793 PointsI'm having the same problem did you find a way to fix it?