尝试在 Swift 上使用 NSJSONSerialization.JSONObjectWithData 2

Trying to use NSJSONSerialization.JSONObjectWithData on Swift 2

我有这个代码

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()

但它在 let task 行失败并出现错误:

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

怎么了?这是 Xcode 7 beta 4、iOS 9 和 Swift 2。


编辑:

问题似乎出在这些行上

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

我删除了这些行,let task 错误消失了。

看起来问题出在 catch 语句中。以下代码不会产生您所描述的错误。

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

我知道你提供的代码应该是正确的,所以你应该考虑向 Apple 提交一个关于这个的错误。

Apple 在 Swift 2 Edit: 许多库中用 ErrorType 替换了 NSError。

所以用 ErrorType 替换你自己对 NSError 的显式使用。

编辑

Apple 已经为 Swift 2 中的多个库完成了此操作,但还不是全部。 所以还是得想好哪里用NSError,哪里用ErrorType。

您也可以假设没有错误:

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

看,妈……没有手!

对于 swift 3 :

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