正在尝试在Swift 2上使用NSJSONSerialization.JSONObjectWithData
我有这个密码正在尝试在Swift 2上使用NSJSONSerialization.JSONObjectWithData,swift,swift2,Swift,Swift2,我有这个密码 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 : Any
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()
但它在让任务与错误对齐时失败:
从类型为(_____;)的抛出函数到的抛出函数的转换无效
非抛出函数类型(NSData?、nsurresponse?、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)")
}
我删除了这些行,让任务
错误消失。问题似乎出现在catch
语句中。下面的代码不会产生您描述的错误
do {
jsonResults = try NSJSONSerialization.JSONObjectWithData(data!, options: [])
// success ...
} catch {
// failure
print("Fetch failed: \((error as NSError).localizedDescription)")
}
<>我意识到你所提供的代码应该是正确的,所以你应该考虑对苹果提出一个错误。 < P>苹果在NSWRRR中用ErrorType在SWIFT 2强> >编辑:< /强>在许多库中。
因此,用ErrorType替换您自己显式使用的NSError
编辑
苹果已经在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)")
}