swiftyjson - Call can throw, but it is marked with 'try' and the error is not handled

限于喜欢 提交于 2019-11-27 16:03:13

You should wrap it into a do-catch block. In your case:

do {
    let session =  URLSession.shared.dataTask(with: url) {
        (data, response, error) in
            guard let data = data else {
            print ("data was nil?")
            return
        }

        let json = JSON(data: data)
        print(json)
    }
} catch let error as NSError {
    // error
}

The SwiftyJSON initializer throws, the declaration is

public init(data: Data, options opt: JSONSerialization.ReadingOptions = []) throws

You have three options:

  1. Use a do - catch block and handle the error (the recommended one).

    do {
       let json = try JSON(data: data)
       print(json)
    } catch {
       print(error)
       // or display a dialog
    }
    
  2. Ignore the error and optional bind the result (useful if the error does not matter).

    if let json = try? JSON(data: data) {
       print(json)
    }
    
  3. Force unwrap the result

    let json = try! JSON(data: data)
    print(json)
    

    Use this option only if it's guaranteed that the attempt will never fail (not in this case!). Try! can be used for example in FileManager if a directory is one of the default directories the framework creates anyway.

For more information please read Swift Language Guide - Error Handling

Probably you need to implement do{} catch{} block. Inside do block you have to call throwable function with try.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!