Eric Eric - 1 month ago 22
JSON Question

cannot invoke 'jsonObjectWithData'

I cannot figure out how to solve this issue.

This comes from a youtube tutorial to build a simple Weather App.
The tutorial was uploaded in March 2015 and therefor written in a previous version of Swift, there it worked, with the current Swift 2 it doesn't.

The error I get is: "cannot invoke 'jsonObjectWithData' with an argument list of type '(NSData, options: nil, error: NSError)'"

func getWeatherData(urlString:String) {

let url = NSURL(string: urlString)

let task = NSURLSession.sharedSession().dataTaskWithURL(url!){ (data, response, error) in
dispatch_async(dispatch_get_main_queue(), {

self.setLabels(data)

})

}

task.resume()

}

func setLabels(weatherData: NSData) {

var jsonError: NSError

let json = NSJSONSerialization.JSONObjectWithData(weatherData, options: nil, error: jsonError)

if let name = json["name"] as? String {

self.ResultLabel.text = name
}
}

JAL JAL
Answer

You need to pass the error pointer into NSJSONSerialization.JSONObjectWithData(...) with &.

let json = NSJSONSerialization.JSONObjectWithData(weatherData, options: nil, error: &jsonError) // &jsonError points to the NSErrorPointer of the NSError object