Blog

  • Tutorial: Using Swifts Codable Protocol

    Parsing JSON into objects is a core part of object orientated programming. Almost every application relies on using a process to decode JSON safely. In Swift now, Apple has provided a mechanism to help simplify this process for developers.

    Swifts Codable protocol maps the coding keys on your object models to the JSON that has been retrieved. This means that developers have to write very little code in the process. We only have to ensure that our coding keys map correctly to the values we are expecting in our JSON.

    Tutorial:

    We are going to make a simple app that uses the Decodable protocol to create Article objects from New York Times’ free article API. It is time to start off with a new single view application and create a UITableView inside your first ViewController.

    If you would like to access the New York Times’ free API you will need to register here:

    https://developer.nytimes.com

    After you have registered you will be given an API key, which you will need to attach to the API call in the Networking class we will build later.

    We are going to start the project by building the model file. This is going to be the structure that our Article will be created from with the JSON that we retrieve from the New York Times API. We are going to define two structures in this file, one will be Articles (plural) and one will be Article (singular).

    Our JSON will be decoded into Articles, which is simply the number of articles in an Integer and an array of Articles. One important thing to remember when using Codable and Decodable protocols is that all of the objects inside the Decodable object must also be Decodable. This means our Article struct also has to be Decodable.

    Now inside our structs, we are going to define our coding keys. These are the strings that will map our JSON values into our objects properties.

    https://gist.github.com/rtking1993/67337dc066295f38c069240154e57fac

    Next, we want to create our ArticleRemote class, this is going to contain our networking code. By putting your networking code into a separate class it will tidy up your view controllers.

    Inside our ArticleRemote class, we just have one static function that will retrieve our Articles in JSON. Once the network call has been completed and we are sure there are no errors we can instantiate a JSONDecoder object, this will decode the JSON into our Articles object.

    https://gist.github.com/rtking1993/84db0ac692f088243ec86b19c0d039c0

    Now we can fill our ArticleViewController with the code required to display the Articles that we have now created using our remote request. We are simply going to display the title for each article and give the ability for the user to tap the cell and be taken to the article.

    https://gist.github.com/rtking1993/37f0c3faadaf75d271873f845ab9235e

    The last thing we want to do is connect up our ArticleViewController to the storyboard. We need to create a UITableView that is constrained to the edges and connect it up to the outlet, datasource, and delegate for the UIViewController.

    Screen Shot 2018-04-08 at 12.39.47 PM

    If you build and run your project now you should get a live list of the latest Technology articles fresh from the New York Times!

    Simulator Screen Shot - iPhone 8 Plus - 2018-04-08 at 14.02.54

    The source code for the finished codable example project is available here:

    https://github.com/rtking1993/CodableTests

  • Tutorial: Firebase Dynamic Lists

    Google’s Firebase platform includes the Real-Time Database. This is a fantastic way to coordinate quickly changing data to your application. The beauty of using this mechanism is the fact that when a change is made to your data, a notification is sent to your application to update the relevant piece of data.

    There are two main advantages of using this push system as opposed to polling the data. Firstly, the changes to the database are sent and displayed on your device almost immediately. The second advantage is that this system doesn’t require downloading all of the data in the list multiple times, but only the data that has changed when it changes.

    Tutorial:

    You can start with a test project that I have already prepared, it has all of the Firebase frameworks that you will require already set up using Cocoapods. This will save you a bit of time and enable me to focus on the more important aspects of Firebases Real-Time Database. The test project is available here:

    https://github.com/rtking1993/FirebaseTest

    Now we should be starting with a single view application template with Firebase frameworks set up and ready. The first thing we should do is get the outlets properly connected to our MainViewController file. We will need a UIView, UIButton, UITextField and a UITableView. Place these onto your storyboard, similarly to what I have done below.

    Screen Shot 2018-03-30 at 3.01.45 PM.png

    Next, we want to connect these objects up to some outlets, which should look something like this in your MainViewController.swift file.

    Screen Shot 2018-03-30 at 3.03.27 PM.png

    We are going to be displaying a list of our items that are going to be connected to the Firebase Database. So we need to have a local instance of our items. Our items are going to be a simple model. Our model will look like this.

    https://gist.github.com/rtking1993/4c0bc66ab37ab125ff92b7224e909295

    This model will give us the ability to instantiate itself, either using regular parameters or a DataSnapshot that we will receive from the firebase server.

    Now we can head over to our MainViewController.swift file and add an array of items. We are going to use a property observer called didSet on our array. The didSet property observer will be fired whenever the items array is set, we can put the code here to reload our table view. This way our UITableView will reload every time our items array is set.

    https://gist.github.com/rtking1993/aed84f4c2edffae4f2053b9ed793d509

    Now that we have an array of items, we can fill our data source methods on our UITableView. If we do this as an extension of MainViewController outside of our class, we can keep the code nice and tidy. Just like the below example.

    https://gist.github.com/rtking1993/69e4cce03241fc6f4f10c9f6d1c314de

    Now we are going to create this class called ItemsRemote. It will allow us to remove networking code out of our MainViewController. It will have methods to post an item to the Database and get all of our items from the Database. Having this class improves the readability of the ViewController and also enables us to have a constant DatabaseReference point for our list of items, this is important so we know we are always reading and writing from the same place.

    https://gist.github.com/rtking1993/7eb1c2c668bc01d80beddceb923690e2

    The last thing we need to do is add the important methods into the MainViewController.

    The MainViewController will start with the viewDidLoad method, so inside here, we will call the method loadItems(). Our loadItems function uses our ItemsRemote class to get the list of items from the database. It then sets the items that it retrieves into our array of items, which will then refresh the table view.

    The other two methods are going to enable us to post items to the server. All we need to do is create the add IBAction which will be called whenever the add button is pressed. We can then use the text inside the UITextField to create an Item and post it to the database using our ItemsRemote class. The last helper function called textFieldFinished just dismisses the keyboard and sets the text of the UITextField to nil after we have finished posting.

    https://gist.github.com/rtking1993/9d118e0a3539680c67eb77eb30184cd7

    If you have followed all of the steps correctly and I haven’t missed anything out, your item list should be working.

    The source code for the finished dynamic item list is available here:

    https://github.com/rtking1993/FirebaseTest/tree/feature/finished

     

  • Tutorial: Writing Unit Tests with XCTest

    Testing is a fundamental part of baking in quality to your codebase. Testing helps quickly check that all the functionality in your app is working and ensures that you are writing better code. Fortunately, with XCTests, writing unit tests for functionality in your app is simple.

    Tutorial:

    To start with, get yourself a test project. I have provided one that you can download here:

    https://github.com/rtking1993/UnitTest-Calculator-Tutorial-Start

    Screen Shot 2018-03-28 at 7.26.28 PM.png

    This application is a simple calculator app that can perform operations on two numbers. If you build and run it on Xcode you should see it working correctly. However, what we are going to do now is add some unit tests to the operation logic of this app to be absolutely sure that things are running as they should.

    The first thing we do is go to File > New > Target. We want to add an iOS Unit Testing Bundle, similar to the image below. This will add a test target to our project and also create some automatic files for us to help get us started.

    9vRSE

    The last thing we want to do before we start writing our tests is to go into the File Inspector on CalculatorInteractor and ensure that our file is available in both the Main and Test target. Your file should have the two ticks for both targets.

    Screen Shot 2018-03-28 at 8.48.04 PM.png

    Then we want to create a new file, call it something like CalculatorInteractorTests and place it amongst your new test files. Now we are ready to write some test functions.

    Every time the unit tests are run, setup is called to perform any tasks that will prepare the tests. We are going to instantiate our CalculatorInteractor in here.

    Our first function is called testAddition(), it is very important that all of your tests start with the word “test”. Otherwise, you will not be able to run them as tests. Inside this function, we are going to instantiate two numbers before calling our calculatorInteractor to perform the addition operation.

    This addition operation will return us a result. We know that 9+4 should give us 13. Because we know this, we can write an XCTAssert, which will check our result against this expectation and succeed or fail depending on whether the check matches. This is how we can be sure that our addition calculation is working correctly.

    https://gist.github.com/rtking1993/7e1b7bad3cbd98a37c77ada2f311a0a0

    Now we have written our first test function, we want to try and write some more for the rest of our operations. Here is a list of some, but not all of the possible tests that could be created to fully test the CalculatorInteractor.

    https://gist.github.com/rtking1993/69f36da3602cc0bd95ade76ebabdbfa7

    Have a go and see whether you can find all of the test cases. This is a great exercise to help familiarize yourself with unit tests.