senty senty - 3 months ago 24
Swift Question

Swift 2 - NSJSONSerialization.JSONObjectWithData Handling Error

I have a JSONParser, but unfortunately I couldn't adapt

NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &error)
bit to Swift 2.0, so I am receiving error:


Extra argument 'error' in call



I found out that I can achieve this with do-try-catch, but I couldn't figure out how to adapt it in my case. Whatever I tried is just throwing another error.

class JSONParser {

let json: AnyObject?
var error: NSError?

init(data: NSData){ // ~this chunk~
self.json = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &error)
}

func array()->NSArray?{
if let jsonResponse: AnyObject = self.json{
return jsonResponse as? NSArray
}
return nil
}

func dictionary()->NSDictionary?{
if let jsonResponse: AnyObject = self.json{
return jsonResponse as? NSDictionary
}
return nil
}
}

Answer

swift3

NSJSONSerialization and its methods are modified, according to the Swift Documents.

do {

    let JsonDict = try JSONSerialization.jsonObject(with: data, options: [])
    // you can now use t with the right type        
    if let dictFromJSON = JsonDict as? [String:String]
 {
        // use dictFromJSON
    }
} catch let error as NSError {
    print(error)
}

Swift2

   init(data: NSData){  // ~this chunk~
     do {
        self.json = try NSJSONSerialization.JSONObjectWithData(data, options: []) as! [String:AnyObject]

     } catch {
        print("error: \(error)")
        self.json = nil
     }
  }

for more information tutorial1, tutorial2

Comments