Real World Example: Fetch JSON using NSURLSession and populate a UITableView Part 2.

Here’s part 1 of this post.

Farhan Syed
iOS App Development
3 min readApr 10, 2017

--

In part 1, we fetched JSON from the web using NSURLSession and stored it into a local array, tableArray.

Let’s get started by opening our Main.storyboard.

Go ahead and delete the default ViewController.

You should now have a blank Main.storyboard.

On the right plane drag and drop a UITableViewController from the Object Library.

Before we go and connect our UITableViewController to our code we need to conform our ViewController.swift to the UITableViewController.

To do so open ViewController.swift.

Change this:

class ViewController: UIViewController

To this:

class ViewController: UITableViewController

Now let’s connect our UITableViewController to our code by opening main.Storyboard and click on the outer part of the controller.

Open the Identity Inspector and change the class to ViewController.

Now we need to make sure this is the Initial View Controller.

Now let’s go back into ViewController.swift to add a few things.

In viewDidLoad add these two lines of code:

self.tableView.dataSource = selfself.tableView.delegate = self

Just to keep things clean and separated let’s create an extension of ViewController.

Put this outside the class braces.

Inside this extension we can add our tableView functions.

Inside cellForRow we need to be able to return a UITableViewCell.

We also need to use our tableArray here to use each value and set it as the cell’s text.

We can do so by adding these two lines.

In our numberOfRowsInSection, we need to return the number of rows our table needs. In this case we would return the count of our tableArray.

As you recall we named our UITableViewCell as “Cell”. We need to declare this in our storyboard.

On the left you will see a file like system, find Cell and click it.

Now in the Attributes Inspector, put Cell as the Identifier.

Now all we need to do is to add self.tableView.reload() in our parseJSON() function.

You can now run your project with Command + R.

There may be some delay in time you see the array in our console to the time it takes our table to populate or may not show up till you click the screen.

This is due to not calling self.tableView.reload() on the main thread.

You should always update the UI on the main thread.

We can do this by simply wrapping our reload with this:

DispatchQueue.main.async {   self.tableView.reloadData()}

Now our table should be a lot quicker to populate.

That’s it! We now have a simple barebones populated UITableView with JSON fetched from the web.

Any comments or suggestions on future posts, please let me know. 😊

If you got lost, I have the full project on GitHub.

--

--