Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

Parsing JSON data in Swift 2.0 for a TableView

I'm able to parse from a sample API fine, but I'm having issues storing that data to be used in a TableView in the same controller. Anyone have any good experience with this? I need to create a dictionary or array in this closure but be able to access it outside of it to display in the tableview and get the count.

Thanks for any help.

override func viewDidLoad() {

    super.viewDidLoad()

    let url = NSURL(string: "http://localhost:3000/todosOpen")!

    let session = NSURLSession.sharedSession()

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

                do { let jsonResult = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as! NSArray

                    //check if item exists then print the 1st object's description
                    if jsonResult.count > 0 {
                        if let description = jsonResult[0]["description"] as? NSString {
                            print(description)

                            //store data in some type of dictionary or array to be used outside of this closure in the table view

                        }
                    }


                } catch {
                    //put error here
                }

            }
        }
    }


    task.resume()

}

2 Answers

Unfortunately, it's not as simple as that. The task executes asynchronously, so even if you set a class property to the results that come back from the HTTP call, nothing would happen because all other processing would most likely be done by then.

There are 2 solutions to look into:

  1. Give the dataTaskWithURL a callback function to execute when the task completes, and you can pass the results to that function. The callback function would take the data and update the UI
  2. Call a function that's defined on your TableView class directly from the success function that you have. This function would then take the data it was given and update the UI

Hope this helps! If you still have some trouble, just shout out. You might find this post helpful. It get's a bit more complicated the further down you go, so stick to what you're comfortable with.

Thanks a lot Jake Adams. That makes total sense now, I wasn't thinking it through. I just created a function on success like you said and can update the UI.