我写了这段代码:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.securityPolicy.allowInvalidCertificates = YES; // not recommended for production
在更新到XCode 7后,它给了我这个错误:抛出类型(_,_,_)抛出函数的转换无效 - > Void to non-throwing function type(NSData?,NSURLResponse?,NSError?) - >虚空。这是排队,在哪里让任务。
由于
答案 0 :(得分:45)
您需要实现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($0["body"] ?? "", terminator: "\n\n") }
// self.tableData = results
// self.Indextableview.reloadData()
}
}
} catch {
print("JSONSerialization error:", error)
}
}
print("\nDownload started:", start.description(with: .current))
答案 1 :(得分:6)
正如Leo所建议的那样,您的问题是您使用的是try
,而不是do
- try
- catch
内部,这意味着它会推断该闭包被定义为抛出错误,但由于它没有被定义,所以你得到了这个错误。
所以,添加do
- try
- catch
:
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!) { data, response, error in
print("Task completed")
guard data != nil && error == nil else {
print(error?.localizedDescription)
return
}
do {
if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {
if let results = jsonResult["results"] as? NSArray {
dispatch_async(dispatch_get_main_queue()) {
self.tableData = results
self.Indextableview.reloadData()
}
}
}
} catch let parseError as NSError {
print("JSON Error \(parseError.localizedDescription)")
}
}
task.resume()
}
答案 2 :(得分:0)
在Swift 2中,将所有NSError
替换为ErrorType
试试这个。
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()
}
答案 3 :(得分:0)
更改代码中的错误类型try-catch对我有用。
“用ErrorType替换所有NSError”