Connecting iOS App to MySQL Database with Swift 5 Using Protocol Delegation and MVC Architectural Pattern

Jose Ortiz Costa
9 min readJun 9, 2019

This article was written using iOS 12.2, Xcode 10.2.1, Swift 5, PHP 7 and MySQL 5.7.25. In addition, this article requires some basic knowledge about those technologies, protocols with Swift, and MVC architectural design in iOS

The following article may help you to get started with protocols in Swift

In this tutorial, we’ll cover the following concepts:

  1. Connecting a iOS app to a MySQL database and retrieve data from it.
  2. Protocol Delegation.
  3. Model, View, Controller (MVC) architectural pattern for iOS apps.

There are different storage technologies available for iOS developers such as Sqlite, Core Data, or Realm. However, when creating iOS applications I often run into the need to handle data from a database that may be also shared with my web site, or my Android app.

In this article, I will implement an iOS app from scratch to illustrate that concept. and I will highlight one of the methods I commonly use to achieve this communication; Protocol Delegation using the architectural pattern known as Model, View, Controller (“MVC”), a method for designing the data flow in your project.

Let’s get started!!!

The Holidays App

The holidays app will provide a basic functionality using two interfaces, a UIViewController and UITableView. The user enters a month in a UITextField in the UIView, and after clicking a UIButton, the app will show all the holidays in that month in a UITableView.

The Server

The server of this app host the database and the PHP script which is the bridge communication between our app and the database. For the sake of simplicity, I created a server in my localhost with MAMP. But, the database and the PHP script can also be hosted in a remote server.

  1. The Database

Let’s create a simple database “MyHolidaysDatabase”. This database contains one table “Holidays” with the attributes “hid”, “month”, “day”, “year” and “description”. This is how my new table looks like after some data is inserted into.

2. The PHP Script

The following PHP script “holidays.php” takes the month sent from the client (iOS app) by a POST request, and based on that condition, retrieves all the holidays in the database for that month. The data from the database is processed and encoded into a JSON. It is important to notice that I provided some basic security in the script using SQL prepared statements to avoid a SQL injection attack.

holidays.php

The Client

Our iOS app represents the client for this application. The client sends data to the server, the server, then encodes the data into a JSON, and sends its response to our iOS app.

Let’s create the project. Open Xcode and create a new project with Swift like the one below. For this tutorial, I deselected the Unit Test and UI test.

Creating the project with Xcode

First of all, in order to follow the MVC architectural pattern in our app, and for a better organization of our code, we need to create three new groups in our project tree called ‘ViewControllers’, “Views”, and “Models”. Then, move the ViewController.swift file into the “ViewController” group, and create a tree structure like the one in the below figure.

Now is UI design time!!!.

Open the Main.storyboard file to access your root ViewController. Then, add a button and a textfield to the view controller. Finally, from the library tools located on the top right menu of Xcode, select a new UITableViewController, drag and drop it into the storyboard scene. At this point, the project tree and the interface design of your project should be similar to the one in the following figures.

Project Tree Structure and UI Interface Design

Since one of the main functionalities of our app will be connecting and handling data provided by our server, it needs to implement the NSAppTransportSecurity Protocol. Right click on the info.plist file, open as, source code, and add the highlighted lines to the source code of your info.plist file.

The Code

Let’s get started with the coding part of our app. First of all, it is a good practice to create a reusable API that must handle all our URLSession requests and responses in our app independently of the data being returned by the server. To put it differently, our API is not interested in the type of data that is being processed. It, instead, is interested in the data’s integrity. This API will perform a request that will be handled by our server, and will download the data from the JSON generated by our server’s response after the request. Finally, the Protocol Delegation mechanism will handle communication between our API, models, ViewControllers and Views

The Network API

First of all, open your Network.swift and copy and paste the following code:

Let’s break the Network API per parts:

Downloadable protocol: this protocol is in charge of passing the data downloaded to other models or view controllers that implement this protocol. This mechanism of communication between iOS interfaces is called Protocol Delegation. There are several mechanism to pass data between controllers in iOS such as calls backs, and notifications. However, I always use delegation in all my apps because in my opinion this mechanism is cleaner, easy to be tested and good to be implemented in a MVC pattern architecture.

URLServices enumerator: all the URL end points to the PHP scripts in our server go here.

Network class: creates the request and response methods that will handle the communication between the client and the server. As you can see, the response method takes the request and a complexion block as parameters. Since the Session Shared Data Task method is asynchronous, the completion block will make sure that the data is available when we need it.

Dictionary and CharacterSet extensions: they provide escape and parsing functionality to the URLSession

The HolidayModel

The holiday model is in charge of decoding the data downloaded in the response from the Network API. The data downloaded is then parsed, and decoded into our Holiday struct model.

The Holiday struct is the model where our data will be decoded. It is important to notice that the Holiday struct implements the Decodable protocol in order to meet all the decoding rules. Also is important to point out that the variables in the struct need to have exactly the same name and data type that the attributes in our Holiday table from the database.

The HolidaysModel class instantiates a weal delegate property from our Downloadable protocol, and a NetworkModel object (our API). Notice how the Downloadable data type is set to Optional because we need to take care of nil responses from the server.

The downloadHolidays function inside the HolidaysModel creates a URLSession request, and then pass that request to the response method from our Network API object. Finally, the response is parsed and decoded into the Holiday model in line 19. Then, protocol delegation is used in line 20 to invoke the didReceiveData() method from the Downloadable protocol. Finally, this data will be available, and ready to be handled for all the ViewControllers implementing the Downloadable protocol.

ViewControllers

Now that all our models have been implemented, let’s see how our Controllers are implemented.

Here is the code for thee ViewController.swift file.

===

In this file, we created an outlet in line 4 to programmatically handle the month values entered by the user into the UITextfield. Next, an action function has been created to handle all the functionality after the user clicks on the find holidays button. Once the user enters a month and click on the button, the findHolidays method will create the parameters, and those will be passed to the downloadHolidays method from our HolidaysModel object.

The ViewController needs to be conformable with our Downloadable protocol in order to have the data in the model decoded available after the user click the find holidays button, In order to conform to the Downloadable protocol, we create an extension of the ViewController class which implement the didRecieveData() method from our protocol. Thanks to the protocol delegation mechanism, once the flow of the program reach this method, the model decoded with the data downloaded from our server is already available for us, and we only need to instantiate the UITableViewController to present the data.

The HolidaysViewController

Since we added a UITableViewController manually to the storyboard scene, and the HolidaysViewController class will be in charge of handling all the events from that controller. Therefore, (1) the file must be connected to the controller, and (2) we need to set a identifier for our prototype cells

(1) Click on the UITableViewController, and in the attributes tool show the identity inspector and set the class attribute to the HolidaysViewController file as indicated in the left figure below

(2) Next, click on the cell below the prototype cells text, and in the attribute tool show the attributes inspector and set the table view cell identifier attribute to ‘holidaysid’.

Setting class and cell identifier

Now that the UITableViewController is connected to its file, and the cell view has an identifier, let’s implement the HolidaysViewController class that will provide functionality to show all the holidays retrieved from our database in its UITableViewController.

First of all, an instance of our Holiday model needs to be wrapped into an array because most of the time, we may be retrieving more than one Holiday model from the view controller passing the data. Then, we implement all the methods from the UITableViewController

For the sake of simplicity, we only return one section in our UITableViewController. The number of cells returned is based on the number of elements in the Holiday model array.

Our last method in this class, defines the content shown in the cells. At this point, a custom cellView can be created to show custom elements in our cells. However, I decided to create an extension of the UITableCellView because I wanted to create my own text content in the cell’s textfield defined by the method:

cell.makeCustomText(model: holiday)

The CellView.swift File

As you can see in this code, the makeCustomText method is an extension in the UITableViewClass which creates my custom text content for the cell. Once called, it will show, in the cell’s textfield, the holiday description, the month, the day and the year of the holiday nicely formatted.

Let’s test the functionality of our app

User enters a month
All the holidays for that moth are retrieved from the database

Wrapping Up

In this tutorial, we created a basic iOS app that illustrates three important concepts to take into consideration in iOS development. (1) Connect to a MySQL database, hosted locally or remotely, from our iOS app. (2) Apply the Protocol Delegation mechanism to communicate and pass data between models and view controllers in our app, and (3) Implement a MVC architecture to get a better flow in the data, and a better code organization in your project.

You can clone or download the complete project from my Github repository

Enjoy!!!.

--

--

Jose Ortiz Costa

Software Engineer, Computer Science Instructor at SFSU and IOS Enthusiast