Real World Example: Fetch JSON using NSURLSession and populate a UITableView Part 1.
In past posts I’ve covered topics such as functions, loops, dictionaries, string interpolation, conditional statements and also switch cases.
In this post I will try to use many of the topics I’ve covered by creating a very barebones iOS application that fetches some JSON from a web API, then we will use this data to populate a simple UITableView.
While building this app we will be utilizing:
- Functions
- Arrays
- Dictionaries
- NSURLSession
- UITableViewController
Let’s get started.
First we need some JSON
with a url to access it.
While preparing for this post, I wrote some super simple JSON
and stored it at myjson.com.
You can use mine here: https://api.myjson.com/bins/vi56v.
Visit the link, you’ll see simple JSON where there’s an array(list) of companies.
Open Xcode
Let’s open Xcode and create a single view application.
Navigate to ViewController.swift.
Your default ViewController.swift
should look like this:
Let’s start writing some code.
Start by creating a function called parseJSON()
after viewDidLoad()
.
This is where we are going to have our network logic to grab our JSON
from the web API.
Let’s define our url:
We are using let
instead of var
because we won’t be manipulating this url.
Now let’s add NSURLSession
:
Inside this task block is where we will check for errors and put our data into an array to populate our table.
Let’s check for any errors & if theres any empty data:
I’ll explain why we aren’t using
if else statements
later in another post.Update: I wrote a post on guards. Check it out.
Now we need to convert our JSON
to NSDictionary
with JSON
Serialization
.
Now what we have a NSDictionary
, we can tap into “companies” key and put all the values into an NSMutableArray
.
We then would loop
into this array and add each value to a local defined array.
Let’s define our local array.
Now that we have a local array defined we can move onto putting our “companies” into our tableArray
.
We need to add task.resume()
outside our task block.
Should look like so:
Now call parseJSON()
in viewDidLoad
and you should see the array in the console.
Stay tuned…
I remember when I was learning to program for iOS, super long articles would be pretty frustrating and hard to follow so that’s why I am breaking this topic up into two parts.
So stay tuned for part 2 of this post where I’ll cover how to use the tableArray
to populate a UITableView
👍 .