在swift3中抓取JSON时出错

时间:2017-03-04 07:22:28

标签: json swift swift3 swift2 getjson

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”作为调用中的额外参数'错误'

please help me in sorting this error or please suggest me link for grabing JSON library.thanks in advance.

1 个答案:

答案 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)
}