Duck
Duck

Reputation: 35953

Trying to use NSJSONSerialization.JSONObjectWithData on Swift 2

I have this code

let path : String = "http://apple.com"
let lookupURL : NSURL = NSURL(string:path)!
let session = NSURLSession.sharedSession()

let task = session.dataTaskWithURL(lookupURL, completionHandler: {(data, reponse, error) in

  let jsonResults : AnyObject

  do {
    jsonResults = try NSJSONSerialization.JSONObjectWithData(data!, options: [])
    // success ...
  } catch let error as NSError {
    // failure
    print("Fetch failed: \(error.localizedDescription)")
  }

 // do something

})

task.resume()

but it is failing on the let task line with the error:

invalid conversion from throwing function of type (__.__.__) throws to non throwing function type (NSData?, NSURLResponse?, NSError?) -> Void

what is wrong? This is Xcode 7 beta 4, iOS 9 and Swift 2.


edit:

the problem appears to be with these lines

  do {
    jsonResults = try NSJSONSerialization.JSONObjectWithData(data!, options: [])
    // success ...
  } catch let error as NSError {
    // failure
    print("Fetch failed: \(error.localizedDescription)")
  }

I remove these lines and the let task error vanishes.

Upvotes: 6

Views: 9044

Answers (4)

Nyakiba
Nyakiba

Reputation: 862

For swift 3 :

 do {
    jsonResults = try JSONSerialization.JSONObject(with: data!, options: [])
// success ...
 } catch {// failure
    print("Fetch failed: \((error as NSError).localizedDescription)")
}

Upvotes: 0

Chris Livdahl
Chris Livdahl

Reputation: 4740

You can also assume no errors with:

let jsonResults = try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions(rawValue: 0)) 

Look, Ma... no hands!

Upvotes: 2

Gerd Castan
Gerd Castan

Reputation: 6849

Apple replaced NSError with ErrorType in Swift 2 Edit: in many libraries.

So replace your own explicit usage of NSError with ErrorType.

Edit

Apple has done this for several libraries in Swift 2, but not all yet. So you still have to think where to use NSError and where to use ErrorType.

Upvotes: 2

Mick MacCallum
Mick MacCallum

Reputation: 130193

Looks like the issue is in the catch statement. The following code won't produce the error you've described.

do {
    jsonResults = try NSJSONSerialization.JSONObjectWithData(data!, options: [])
    // success ...
} catch {
    // failure
    print("Fetch failed: \((error as NSError).localizedDescription)")
}

I do realize that the code you've provided is supposed to be correct, so you should consider filing a bug with Apple about this.

Upvotes: 9

Related Questions