Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

iOS Build a Weather App with Swift (Retired) Concurrency Using Our JSON Data

humongous problem , xcode keeps complainig that "type NSData? does not conform to protocol AnyObject."

let dataObject = NSData(contentsOfURL: location) let weatherDictionary: NSDictionary = NSJSONSerialization.dataWithJSONObject(dataObject, options: nil, error: nil) as NSDictionary })

i tried adding a exclamation mark but still doesnt work

2 Answers

In your code

let dataObject = NSData(contentsOfURL: location) 
let weatherDictionary: NSDictionary = NSJSONSerialization.dataWithJSONObject(dataObject, options: nil, error: nil) as NSDictionary

On the second line you're using dataWithJSONObject() -- getting an NSData object from a JSON object, but what you want is the opposite-- JSONObjectWithData() which returns an NSDictionary as an AnyObject from an NSData object, which you then downcast appropriately.

let dataObject = NSData(contentsOfURL: location)
let weatherDictionary: NSDictionary = NSJSONSerialization.JSONObjectWithData(dataObject!, options: nil, error: nil) as NSDictionary

Also you do need to unwrap the dataObject returned by the NSData() constructor on the line above with a !. Since the video was made, Swift has been updated and it now returns an optional rather than an implicitly unwrapped object.

Max Hirsh
Max Hirsh
16,761 Points

I think James has the right answer. I was having a lot of issues because of the syntax changes with the xcode update. What helped was unwrapping the dataObject as dataObject!.

Another strange thing I ran into is that my code did not run properly even with the corrections until I restarted xcode, then deleted and retyped everything from this video with the new syntax. I think something about trying to use the old syntax first made xcode not function properly... Or I could have made a typo the first time through :D.