Connect your iOS App to your Web Service
This will be an in depth tutorial in which we are going to completely create all of the following from scratch for ourselves:
- SQL database in the cloud
- A RESTful web service to connect to our SQL Database
- An iOS App use that will use web service to retrieve the data
The high level architecture is as follows, we will be implementing all steps in this tutorial. We will touch on each step brief, not too in depth, but enough to understand how it all comes together.
Creating the SQL Database in the cloud
First of all we need to sign up to a service to host our SQL Database in the cloud. I recommend BlueHost as I use it and have found it to be very flexible in terms of their hosting plans and offers. In terms of the plan to create a SQL database in the cloud we only need the “basic” one which will cover both of them. Otherwise if you already have your own hosting you can skip to the step where we create a SQL database and follow along.
You can sign up for BlueHost here.
Once you have setup an account head over to the control panel and go to MySQL Databases.
Create a new database called, “Students”. Create a new user called teacher with the Password P@ssw0rd.
Then add the teacher user to your students database. Give the user all privileges.
Then go back to database tools, and phpMyAdmin.
You will be taken to a page where you see your username/website on the left, along with your SQL databases under it once you expand it out. Select the students database and create a new table called classes.
After you have created the table the next screen will let you add the columns to the table. Add the following columns to the table (Name, Room, Teacher Name) all with the Type VARCHAR and Length as 99.
Next up go to the Insert tab and add the following values to our students table.
If you head on over to the browse tab you are able to see the data you added to the table! Fell free to have a play around and add more data, SQL is pretty simple once you get the hang of it.
Creating a restful web service
Now it’s time to create a restful web service. This will get the classes table from our students database, and return it in a json format for our app to use. Typically I would write this service in node js (I prefer this for server side programming, and it is quite popular). However to keep this tutorial simple I will be using php this time around, if there is interest in how to set this up in node js let me know in the comments below!
<?php // Create connection $con=mysqli_connect("localhost","username","password","dbname"); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } // Select all columns from the Classes table $sql = "SELECT * FROM classes"; // Check if there are results if ($result = mysqli_query($con, $sql)) { // If so, then create a results array and a temporary one // to hold the data $resultArray = array(); $tempArray = array(); // Loop through each row in the result set while($row = $result->fetch_object()) { // Add each row into our results array $tempArray = $row; array_push($resultArray, $tempArray); } // Finally, encode the array to JSON and output the results echo json_encode($resultArray); } // Close connections mysqli_close($con); ?>
In the first line for connection replace them with the database user credentials you setup – this tutorial used the following:
username = teacher
password = P@ssw0rd
dbname = students
Save the file as getClasses.php, then head back over to your cpanel and select File Manager, and set the home directory as the web root. Then select upload, and select your getClasses.php. This will upload your file to the web root of your website. So in my case its www.seemuapps.com/getClasses.php to access it, yours will be different. Replace seemuapps with your website!
Now if I navigate to www.seemuapps.com/getClasses.php I will see the following:
Create the iOS App to access our web service
Now this is done its time to create our iOS App to access our web service! Create a new single view application and change viewController.swift to match the following:
import UIKit class ViewController: UIViewController { struct Class: Codable { let name: String let room: String let teacher: String enum CodingKeys : String, CodingKey { case name = "Name" case room = "Room" case teacher = "Teacher Name" } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. let url = URL(string: "http://seemuapps.com/getClasses.php") // Load the URL URLSession.shared.dataTask(with:url!, completionHandler: {(data, response, error) in // If there are any errors don't try to parse it, show the error guard let data = data, error == nil else { print(error!); return } let decoder = JSONDecoder() let classes = try! decoder.decode([Class].self, from: data) // Print out the classes to the console - try sticking this in a table view :) for myClass in classes { print(myClass.name) print(myClass.room) print(myClass.teacher) } }).resume() } }
There are two things that this code is doing:
- We create a structure called Class – this is to match the JSON structure for class we have in our web service. The coding keys enable us to match our structure properties to the JSON ones as they cant include spaces, and best practice is for it to be lower case
- We then set the URL to our web service. Once it’s loaded we setup a JSON decoder to put the data from this web service into the variable “classes” which is an array of our Class struct object
- We then loop over each class object in the array and print it to the console
This will result in the following output:
Introduction to XCode CS101 Bill Jobs UX Design for iOS CS222 Dr Gray
See if you are able to build this out and put the information we got from our web service into a table view 🙂