class Get {
class func JSON(url:String,callback:@escaping (NSDictionary)->()) {
requestJSON(url: url,callback: callback)
}
class func requestJSON(url:String,callback:@escaping (NSDictionary)->()) {
var nsURL = NSURL(string: url)
let task = URLSession.shared.dataTask(with: nsURL as! URL) {
(data,response,error) in
var error:NSError?
var response = JSONSerialization.JSONObjectWithData(data, options: JSONSerialization.ReadingOptions.MutableContainers, error: &error) as NSDictionary
callback(response)
}
task.resume()
}
}
在此行中获取错误“var response = JSONSerialization.JSONObjectWithData(data,options:JSONSerialization.ReadingOptions.MutableContainers,error:& error)as NSDictionary”作为调用中的额外参数'错误'
答案 0 :(得分:0)
您应该将该方法包含在try...catch
块中。
只需更换这两行
var response = JSONSerialization.JSONObjectWithData(data, options: JSONSerialization.ReadingOptions.MutableContainers, error: &error) as NSDictionary
callback(response)
与
do{
let jsonObject = try JSONSerialization.jsonObject(with: data, options: .mutableContainers)
if let response = jsonObject as? NSDictionary{
callback(response)
}
}
catch{
print(error)
}
您也可以这样做
if let response = (try? JSONSerialization.jsonObject(with: data, options: .mutableContainers)) as? NSDictionary{
callback(response)
}