Martin Mikusovic Martin Mikusovic - 5 months ago 79
iOS Question

Invalid conversion from throwing function of type (_,_,_) throws -> Void to non-throwing function type (NSData?, NSURLResponse?, NSError?) -> Void

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.

Thanks

Answer

You need to implement Do Try Catch error handling as follow:

func getjson() {
    let url = NSURL(string: "https://api.whitehouse.gov/v1/petitions.json?limit=100")!
    let task = NSURLSession.sharedSession().dataTaskWithURL(url) { (data, response, error) -> Void in
        print("Task completed")
        if let data = data {
            do {
                if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary {
                    dispatch_async(dispatch_get_main_queue(), {

                        if let results: NSArray = jsonResult["results"] as? NSArray {
                            self.tableData = results
                            self.Indextableview.reloadData()
                        }
                    })

                }
            } catch let error as NSError {
                print(error.localizedDescription)
            }
        } else if let error = error {
            print(error.localizedDescription)
        }
    }
    task.resume()
}