George Wisten George Wisten - 4 months ago 13
Swift Question

Extra argument error (I don't understand it)

My previous question: I don't understand this error: extra argument 'error' in call

I have tried to change my code from

var urlData: NSData? = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error:&reponseError)


to

var urlData: NSData?

do {
urlData = try NSURLConnection.sendSynchronousRequest(request, returningResponse:&response){
}
} catch let error as NSError {
print(error.localizedDescription)
}


but I still get an error saying "Extra argument 'returnResponse' in call". Could someone help me fix this? I'm also getting "Extra argument 'error' in call" on this line

let jsonData:NSDictionary = NSJSONSerialization.JSONObjectWithData(urlData!, options:NSJSONReadingOptions.MutableContainers , error: &error) as NSDictionary

Answer

I recommend to use this modern API

NSURLSession.sharedSession().dataTaskWithRequest(request) { (data, response, error) in
  if error != nil {
    print(error!)
  } else {
    do {
      let jsonData = try NSJSONSerialization.JSONObjectWithData(data!, options:[]) as! [String:AnyObject]
      print(jsonData)
      // parse jsonData here and then update the UI
    } catch let error as NSError {
      print(error.localizedDescription)
    }
  }
}.resume()

In Swift don't use Foundation collection types (NSArray, NSDictionary) unless you have absolutely no choice.