尝试在Swift 2中使用NSJSONSerialization.JSONObjectWithData

6
我有这段代码。
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行失败,出现以下错误:

从可抛出函数类型(__.__.__)的抛出进行无效转换至非可抛出函数类型(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 错误消失了。

4个回答

9

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

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

我知道你提供的代码应该是正确的,所以你应该考虑向苹果报告此问题。


2
您可以假设没有错误出现:
let jsonResults = try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions(rawValue: 0)) 

Look, Ma... no hands!


2

在Swift 2中,苹果公司用ErrorType替换了NSError(编辑:在许多库中)

因此,请使用ErrorType来替代您自己显式使用的NSError。

编辑:

苹果公司已经在Swift 2中对几个库进行了更改,但并不是所有库都这样做了。因此,您仍然需要考虑何时使用NSError以及何时使用ErrorType。


0

对于 Swift 3:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接