Last tutorial we looked at coding our GET request to retrieve data from one of the APIs we had written in our Spring Boot application. We didn’t do much with the data that was returned other than printing it out into the XCode console to check that it was working as we had expected it to. This tutorial we’re actually going to go through how we can store this data into an object and display it inside of a UITableView.

Creating our Game.swift Object

So before we go ahead and do anything else, the first thing we want to do is create a new swift file called Game which will represent the JSON data of a single game object returned from our backend application. Once you’ve done this, your XCode project directory might look something like…

So before we start adding anything to this new Game.swift file, I should probably go into a little more detail of why we’re creating this to begin with. Why can’t we just keep our data stored inside of a [[String: AnyObject]] like we’re doing currently? The thing is, you CAN keep it in this format if you’d like (for simple projects such as this)… but I wouldn’t recommend it. The main reason being is that it is A LOT more difficult to maintain and it is a huge pain to retrieve particular fields. By creating our Game model in Swift, we can define one init that will map JSON to it’s appropriate fields in Game.swift which will grant us a hell of a lot easier access to particular data fields.

With that being said, I’m going to mock the JSON fields in our new Game.swift file so that it looks as follows…

import Foundation class Game { var id: Int ? var desc: String ? var title: String ? var releaseDate: String ? init (data: [ String : AnyObject ]){ id = data[ "id" ] as ? Int desc = data[ "description" ] as ? String title = data[ "title" ] as ? String releaseDate = data[ "releaseDate" ] as ? String } }

Cool, so that is our Game class setup. Now we can easily convert our JSON data retrieved from the server into this model.

Storing JSON into an Array of Game.swift Objects

Let’s go ahead and take the data we retrieved from our API and store it into an array of objects. I’m going to create a new function inside of our ViewController.swift file that will do the following…

Take a String parameter which will be represent the title of a game we would like to search for Call our Request.get method to retrieve data from the server (based on the title provided) Take the data we retrieved from this method call and populate an array of Game objects

So it’s going to look something like this…

var gameResults = [Game]() func searchForGamesByTitle(title: String ){ Request.get(requestUrl: Constants.URL.searchGamesByTitle + title) { (results) in OperationQueue.main.addOperation { // Get back onto the main thread after our Asynchronous call for jsonGame: [ String : AnyObject ] in results { self .gameResults.append( Game(data: jsonGame) ) // initialize + add game object into our array } } } }

If you’d like to see what my entire ViewController.swift file looks like, check out the gist here.

Great, so we have a function to populate an array with Game objects. Now we can use this array to display data inside of a UITableView. Let’s go ahead and do that.

Creating The UITableView

Before we do this, I’ll just mention that I’ll be adding a gist to the end of this section that will have the complete source code for our ViewController.swift file so don’t worry if you’re having a hard time following along.

We’re going to be using Storyboard to create our UITableView within our UIViewController.

Once you’ve added in your UITableView and connected it to your ViewController.swift file, we need to add UITableViewDelegate and UITableViewDataSource into our class which will look something like this…

class ViewController: UIViewController , UITableViewDelegate , UITableViewDataSource

You might notice that your project will now have errors. That’s okay, to fix this we need to override a few functions from UITableViewDelegate and UITableViewDataSource, but before doing so I’m going to create another function within our ViewController.swift file to setup the UITableView we have just connected which will look like this…

func setupTableView(){ self . tableView . delegate = self self . tableView . dataSource = self self . tableView . register ( UITableViewCell . self , forCellReuseIdentifier: "cell" ) self . tableView . tableFooterView = UIView () // remove empty cells from tableView }

We’ll call this in our viewDidLoad() function.

The first datasource method we will need to override will look as follows…

func numberOfSections(in tableView: UITableView ) -> Int { return 1 }

We’re only going to need one section for our UITableView, so we can return a constant value of 1.

We now need to define the amount of rows we will need in our UITableView. Since we’re going to be storing one game per row based on the results of our search function, this value will change dynamically based on the number of items found in our gameResults array we created earlier. To do this, we’ll override the following delegate method as follows…

func tableView( _ tableView: UITableView , numberOfRowsInSection section: Int ) -> Int { return gameResults . count }

Lastly, we need to add some content to each row’s cell. In this case, we will display the title of the game. To do so, we need to override another delegate method which will look something like…

func tableView( _ tableView: UITableView , cellForRowAt indexPath: IndexPath ) -> UITableViewCell { let game = gameResults [indexPath. item ] let cell = tableView. dequeueReusableCell (withIdentifier: "cell" , for: indexPath) cell. textLabel ?. text = game. title // set the game title as the cell's text label return cell }

This is a very simple example. If we wanted, we could create a custom cell to show other values within our game object such as the description, release date, etc.

If you want to double check that you have all of the code setup properly in your ViewController.swift file, check out this gist here. You’ll notice that I added searchForGamesByTitle(title: “mario“) into the viewDidLoad() function. This is just so that we can populate our array for the sake of testing. Otherwise, in the future we could add in some sort of search bar that would take user input and from that input perform a search based on the provided value. Anyways, let’s run our application to check that our UITableView is working as we expect.

After running mine in a simulator, I’m able to see that the results returned from our search function are in fact being displayed appropriately inside of the UITableView. Yours should hopefully look something like this (depending on the data you have in your database)…

Cool! So we’ve managed to map the JSON representation of our game objects retrieved from our Spring Boot application into Swift objects and we’ve learned how we can display these results within a UITableView. This was a bit of a longer one, so I’ll wrap it up here.

Next tutorial we’ll learn how we can write a POST request in Swift so that we will be able to create comments on a particular game.

Have any questions, comments, suggestions? Having issues getting your project to this stage? Leave a comment and I’ll be happy to get back to you.