Josh Carsell Josh Carsell - 2 months ago 9
JSON Question

Error parsing json in Swift

I am having an error when trying to parse some JSON from a Google blog.

The error I am receiving is

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


I have Googled around and I know it is something to do with catching the error but I cannot figure out exactly what it is, any help would be greatly appreciated:

import UIKit
import CoreData

class MasterViewController: UITableViewController {

var detailViewController: DetailViewController? = nil
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.

let url = NSURL(string: "https://www.googleapis.com/blogger/v3/blogs/10861780/posts?key=AIzaSyBwmI4AzMnBmr7oSVeL0EHdzMjXV1aATnQ")

let session = NSURLSession.sharedSession()

let task = session.dataTaskWithURL(url!, completionHandler: { (data, response, error) -> Void in
if error != nil {
print(error)
} else {
//print(NSString(data: data!, encoding: NSUTF8StringEncoding))

do {

let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
if jsonResult.count > 0 {

if let items = jsonResult["items"] as? NSArray {
for items in items {
print(items)

}

Answer

Try this. i corrected your errors, added some braces only.

override func viewDidLoad() {
  super.viewDidLoad()

 let url = NSURL(string: "https://www.googleapis.com/blogger/v3/blogs/10861780/posts?key=AIzaSyBwmI4AzMnBmr7oSVeL0EHdzMjXV1aATnQ")

let session = NSURLSession.sharedSession()

let task = session.dataTaskWithURL(url!, completionHandler: { (data, response, error) -> Void in

  if error != nil {
    print(error)
  } else {
    //print(NSString(data: data!, encoding: NSUTF8StringEncoding))
    do {

      let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions(rawValue: 0)) as! NSDictionary
      if jsonResult.count > 0 {

        if let items = jsonResult["items"] as? NSArray {
          for items in items {
            print(items)

          }
        }
      }
    } catch let error as NSError {
      print(error)
    }
  }
})
  task.resume()

} // end braces of view did load 
Comments