user4657
user4657

Reputation: 2713

Extra argument 'error' in call. Compilation error in Swift 2.0

I am currently trying to learn about Swift 2.0 and OAuth integration via this sample application: https://github.com/soundcloud/iOSOAuthDemo

The following snippet below is causing me problems and causing the application to fail in its compilation.

private func requestMe(token: String) {
    let url = NSURL(string: "https://api.soundcloud.com/me.json?oauth_token=\(token)")!
    let request = NSURLRequest(URL: url)
    let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration(),
                               delegate: nil, delegateQueue: NSOperationQueue.mainQueue())

    let dataTask = session.dataTaskWithURL(url) { (data, response, error) -> Void in
        if let jsonOutput = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: nil) as? [String:AnyObject] {
            self.displayMe(jsonOutput)
        }
    }
    dataTask.resume()
}

However when compiling my error handling looks as though it has changed in this version of Swift (2.0) and is causing the following error:

Extra argument 'error' in call with the compilation.

I have reviewed the following stack posting on this issue: Swift: Extra argument 'error' in call

and adjusted my code to try and correct the error handling as such:

let dataTask = session.dataTaskWithURL(url) { (data, response, error) -> Void in
        if let jsonOutput = NSJSONSerialization.JSONObjectWithData(data, options: nil) as? [String:AnyObject] {
            self.displayMe(jsonOutput)
        }
    }
    catch let error as NSError {
        print(error);}
    dataTask.resume()
}

I have also tried changing:

(data, options: nil, error: nil)

to

(data:NSData?, error:NSError?)

However neither of these resolving the issue. Can someone guide me as to what is probably a silly mistake I am making with this error handling.

Thanks in advance!,

Upvotes: 1

Views: 6023

Answers (1)

Eric Aya
Eric Aya

Reputation: 70098

There were several problems with your code: you added catch but forgot do and try. Also you can't pass nil as an option parameter anymore for NSJSONSerialization, and you have to safely unwrap the data optional.

Here's a fixed version:

let dataTask = session.dataTaskWithURL(url) { (data, response, error) -> Void in
    do {
        if let myData = data, let jsonOutput = try NSJSONSerialization.JSONObjectWithData(myData, options: []) as? [String:AnyObject] {
            self.displayMe(jsonOutput)
        }
    } catch let error as NSError {
        print(error)
    }
}
dataTask.resume()

Upvotes: 3

Related Questions