ios 从 (_,_,_) 类型的抛出函数 throws -> Void 到非抛出函数类型 (NSData?, NSURLResponse?, NSError?) 的无效转换 -> Void
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32800341/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Invalid conversion from throwing function of type (_,_,_) throws -> Void to non-throwing function type (NSData?, NSURLResponse?, NSError?) -> Void
提问by Martin Mikusovic
I have written this code:
我写了这段代码:
func getjson() {
let urlPath = "https://api.whitehouse.gov/v1/petitions.json?limit=100"
let url = NSURL(string: urlPath)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(url!, completionHandler: {data, response, error -> Void in
print("Task completed")
if(error != nil) {
print(error!.localizedDescription)
}
let err: NSError?
if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary {
if(err != nil) {
print("JSON Error \(err!.localizedDescription)")
}
if let results: NSArray = jsonResult["results"] as? NSArray {
dispatch_async(dispatch_get_main_queue(), {
self.tableData = results
self.Indextableview.reloadData()
})
}
}
})
task.resume()
}
And after update to XCode 7 it gives me this error: Invalid conversion from throwing function of type (_, _, _) throws -> Void to non-throwing function type (NSData?, NSURLResponse?, NSError?) -> Void. It is in line, where is let task.
在更新到 XCode 7 之后,它给了我这个错误:从类型 (_, _, _) throws 的抛出函数无效转换 -> Void 到非抛出函数类型 (NSData?, NSURLResponse?, NSError?) -> Void。它是在线的,让任务在哪里。
Thanks
谢谢
回答by Leo Dabus
You need to implement Do Try Catch error handling as follow:
您需要按如下方式实现 Do Try Catch 错误处理:
import UIKit
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
extension URL {
func asyncDownload(completion: @escaping (_ data: Data?, _ response: URLResponse?, _ error: Error?) -> ()) {
URLSession.shared
.dataTask(with: self, completionHandler: completion)
.resume()
}
}
let jsonURL = URL(string: "https://api.whitehouse.gov/v1/petitions.json?limit=100")!
let start = Date()
jsonURL.asyncDownload { data, response, error in
print("Download ended:", Date().description(with: .current))
print("Elapsed Time:", Date().timeIntervalSince(start), terminator: " seconds\n")
print("Data size:", data?.count ?? "nil", terminator: " bytes\n\n")
guard let data = data else {
print("URLSession dataTask error:", error ?? "nil")
return
}
do {
let jsonObject = try JSONSerialization.jsonObject(with: data)
if let dictionary = jsonObject as? [String: Any],
let results = dictionary["results"] as? [[String: Any]] {
DispatchQueue.main.async {
results.forEach { print(func getjson() {
let urlPath = "https://api.whitehouse.gov/v1/petitions.json?limit=100"
let url = URL(string: urlPath)!
let session = URLSession.shared
let task = session.dataTask(with: url) { data, response, error in
print("Task completed")
guard let data = data, error == nil else {
print(error?.localizedDescription)
return
}
do {
if let jsonResult = try JSONSerialization.jsonObject(with: data) as? [String: Any] {
if let results = jsonResult["results"] as? [Any] {
DispatchQueue.main.async {
self.tableData = results
self.indexTableView.reloadData()
}
}
}
} catch let parseError {
print("JSON Error \(parseError.localizedDescription)")
}
}
task.resume()
}
["body"] ?? "", terminator: "\n\n") }
// self.tableData = results
// self.Indextableview.reloadData()
}
}
} catch {
print("JSONSerialization error:", error)
}
}
print("\nDownload started:", start.description(with: .current))
回答by Rob
As Leo suggested, your problem is that you're using try
, but not within the do
-try
-catch
construct, which means that it infers that the closure is defined to throwing the error, but since it is not defined as such, you get that error.
作为狮子座的建议,你的问题是,你正在使用try
,而不是内do
- try
-catch
结构,它推断,这意味着关闭被定义为引发错误,但因为它没有被定义为这样的,你得到这个错误。
So, add do
-try
-catch
:
所以,添加do
- try
- catch
:
class func fetchWeatherForLocation(locationCode: String = "", shouldShowHUD: Bool = false, completionHandler: (data: NSDictionary?, error: ErrorType?) -> ()) {
let url = NSURL(string: "myurl")
let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in
if let dataWithKey = data {
do {
let jsonForDataWithTemprature = try NSJSONSerialization.JSONObjectWithData(dataWithKey, options:NSJSONReadingOptions.MutableContainers)
guard let arrayForDataWithKey :NSArray = jsonForDataWithTemprature as? NSArray else {
print("Not a Dictionary")
return
}
let dictionaryWithTemprature = arrayForDataWithKey.firstObject as! NSDictionary
completionHandler(data: dictionaryWithTemprature, error: nil)
}
catch let JSONError as ErrorType {
print("\(JSONError)")
}
}
}
task.resume()
}
回答by Adarsh V C
In Swift 2, replace all NSError
with ErrorType
在 Swift 2 中,全部替换NSError
为ErrorType
Try this.
尝试这个。
##代码##回答by Kishor
Changing the error type in the code try-catch worked for me.
更改代码 try-catch 中的错误类型对我有用。
"replace all NSError with ErrorType"
“用 ErrorType 替换所有 NSError”