0

I am new to programming and learning through a Beginning Xcode book. It is not on Swift 2 (but I am learning through it anyways for now).

In one of the projects it is teaching how to create a twitter-type app. Here is the code:

    func retrieveTweets() {
        tweets?.removeAllObjects()

        if let account = selectedAccount {
            let requestURL = NSURL(string: "https://api.twitter.com/1.1/statuses/home_timeline.json")
            let request = SLRequest(forServiceType: SLServiceTypeTwitter,
                requestMethod:  SLRequestMethod.GET,
                URL: requestURL,
                parameters: nil)

            request.account = account
            request.performRequestWithHandler()
            {
                responseData, urlResponse, error in

                if (urlResponse.statusCode == 200)
                {
                    var jsonParseError : NSError?
                    **self.tweets = NSJSONSerialization.JSONObjectWithData(responseData, options: NSJSONReadingOptions.MutableContainers, error: &jsonParseError) as? NSMutableArray**
                }

                dispatch_async(dispatch_get_main_queue()) {
                    self.tableView.reloadData()
                }
            }
        }

*I get the "extra argument 'error' in call" error at the code with the ** around it (self.tweets...). I've tried putting the "do"/"catch" block code but honestly have no where to put it, or know what I am doing with it :)

Can someone help me on this? Need to know what to change in the bolded code (or around it) to make it work.

Thanks!!

Matt
  • 3
  • 1
  • Remove the error argument, add the try for that line instead. `do{ self.tweets = try NSJSONSerialization.JSONObjectWithData(responseData, options: NSJSONReadingOptions.MutableContainers) as? NSMutableArray} catch _ {//error}` – zc246 Dec 28 '15 at 23:58

2 Answers2

0

Your instinct to use the do/catch block was correct. Because JSONObjectWithData can throw an error, you need to call it with try. The error parameter is unnecessary when dealing with Swift functions that can throw. Try something like this.

if (urlResponse.statusCode == 200) {
    do {
        self.tweets = try NSJSONSerialization.JSONObjectWithData(responseData, options: NSJSONReadingOptions.MutableContainers)
    } catch {

        print("\(error)")
    }
}
Aaron Rasmussen
  • 13,082
  • 3
  • 42
  • 43
0

You are using Swift 2. JSONObjectWithData is now a throwable function. You have to wrap it in a do { try ... } catch block:

if (urlResponse.statusCode == 200)
{
    do {
        self.tweets = try NSJSONSerialization.JSONObjectWithData(responseData, options: [.MutableContainers]) as? NSMutableArray
    } catch let error as NSError {
        print(error.localizedDescritpion)
    }
}
Code Different
  • 90,614
  • 16
  • 144
  • 163