Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to use NSJSONSerialization.JSONObjectWithData on Swift 2

Tags:

swift

swift2

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.

like image 295
Duck Avatar asked Jul 22 '15 13:07

Duck


3 Answers

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.

like image 164
Mick MacCallum Avatar answered Nov 10 '22 08:11

Mick MacCallum


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.

like image 24
Gerd Castan Avatar answered Nov 10 '22 09:11

Gerd Castan


You can also assume no errors with:

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

Look, Ma... no hands!

like image 28
Chris Livdahl Avatar answered Nov 10 '22 08:11

Chris Livdahl