Trying to use NSJSONSerialization.JSONObjectWithData in 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 does not work on the let task line with an error:

an invalid conversion from a cast function of type (__.__.__) throws the type of a non-throwing function (NSData ?, NSURLResponse ?, NSError?) → Void

what's wrong? These are Xcode 7 beta 4, iOS 9 and Swift 2.


edit:

the problem seems to be related to these lines

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

I delete these lines and the let task error disappears.

+6
source share
4 answers

It seems the problem is with the catch statement. The following code will not result in the error described.

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

I understand that the code you provided should be correct, so you should consider the issue with Apple.

+9
source

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

So, replace your explicit use of NSError with ErrorType.

Edit

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

+2
source

You can also make no mistakes:

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

Listen, Ma ... no hands!

+2
source

For quick 3:

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

All Articles