How To Write A Simple Php/mysql Web Service For An Ios App
Today we will learn Swift PHP MySQL. As while developing applications for mobile we need a server for our database. And for this PHP and MySQL is the best option available as it is easy to use and get. So in this Swift PHP MySQL Tutorial we will learn how we can connect our Xcode Project to an external MySQL Database. If you don't want to do additional server side scripting for your application's backend you can go through the Firebase iOS Tutorial, where instead of a server you can use Firebase as you appliation's backend.
If you are looking for a User Registration using PHP and MySQL Tutorial you can visit it from below link.
iOS User Registration Tutorial using PHP and MySQL
Contents
- 1 Swift PHP MySQL Tutorial – Creating Web Service
- 1.1 Creating MySQL Database
- 1.2 Creating PHP Scripts
- 1.3 Testing our Web Service
- 2 Swift PHP MySQL Tutorial – Xcode Project
- 2.1 Creating a New Project
- 2.2 Adding Views
- 2.3 Connecting Views to ViewController
- 2.4 Making POST Request to our Web Service
- 2.5 Making changes in Info.plist file
- 2.6 Testing Your Application
- 2.7 Share this:
- 2.8 Related
In this post we will create a simple Single View App to store some data in our MySQL Database. I will be using the following tools.
- Xcode 7
- PHP Storm
- Xampp (for PHP and MySQL)
The first thing we need is our database so lets create the database.
Swift PHP MySQL Tutorial – Creating Web Service
We need a web service often called REST API, as a medium of communication between our webserver and iPhone application. So first we will create our Web Service that will handle the database insertion. As the below demonstrated method is not recommended, you should check PHP REST API Tutorial instead. But I wanted to make this tutorial as simple as possible so we are creating the web service in simplest way.
Creating MySQL Database
First we will create the MySQL Database. I have created my database model. Below you can see my database model.
This is our database. Its very small and simple as I wanna make this tutorial as simple as possible. To create the above database follow these steps.
- Go to phpmyadmin (localhost/phpmyadmin)and create a new database.
- Now select the database and execute the following SQL statement.
-- tables -- Table: team CREATE TABLE team ( id int NOT NULL AUTO_INCREMENT, name varchar(20) NOT NULL, member int NOT NULL, CONSTRAINT team_pk PRIMARY KEY (id) ); -- End of file.
- And then you will have a database table like the following.
- Now we have our database. We will store the values in this table.
But the values to be stored here will be sent from our iPhone App. And hence we need a communication medium between this database and our iPhone Application. PHP will do this thing for us. So now we will create our web service using PHP.
Creating PHP Scripts
I am going to use PHP Storm IDE, as I love this IDE. So open PHP Storm (You can also use notepad++ or any other text editor).
- Create a new project in the xampp's htdocs folder. I have created MyWebService.
- Create two more directories inside your project, as shown in the below image.
- Inside directory includes create a file named Config.php and write the following code. The below code contains important constant that will be used to connect to our database.
<?php /** * Created by PhpStorm. * User: Belal * Date: 12/08/16 * Time: 7:58 PM */ define('DB_USERNAME', 'root'); define('DB_PASSWORD', ''); define('DB_HOST', 'localhost'); define('DB_NAME', 'iphone');
- Now in the same directory (includes) again create a new file named DbConnect.php and write the following code. This file will create the database connection.
<?php class DbConnect { private $conn; function __construct() { } /** * Establishing database connection * @return database connection handler */ function connect() { require_once 'Config.php'; // Connecting to mysql database $this->conn = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME); // Check for database connection error if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } // returing connection resource return $this->conn; } }
- We need one more file here for the database operation, create a file DbOperation.php and write the following code.
<?php class DbOperation { private $conn; //Constructor function __construct() { require_once dirname(__FILE__) . '/Config.php'; require_once dirname(__FILE__) . '/DbConnect.php'; // opening db connection $db = new DbConnect(); $this->conn = $db->connect(); } //Function to create a new user public function createTeam($name, $memberCount) { $stmt = $this->conn->prepare("INSERT INTO team(name, member) values(?, ?)"); $stmt->bind_param("si", $name, $memberCount); $result = $stmt->execute(); $stmt->close(); if ($result) { return true; } else { return false; } } }
- Now inside api folder create a file named createteam.php and write the following code. This file will actually insert the values to database.
<?php //creating response array $response = array(); if($_SERVER['REQUEST_METHOD']=='POST'){ //getting values $teamName = $_POST['name']; $memberCount = $_POST['member']; //including the db operation file require_once '../includes/DbOperation.php'; $db = new DbOperation(); //inserting values if($db->createTeam($teamName,$memberCount)){ $response['error']=false; $response['message']='Team added successfully'; }else{ $response['error']=true; $response['message']='Could not add team'; } }else{ $response['error']=true; $response['message']='You are not authorized'; } echo json_encode($response);
- Yeah our web service is ready.
- Now we need to know the IP of your xampp server you can easily get it by using ifconfig command. Open terminal and write ifconfig and hit enter.
- So we have the IP, now we can write the URL of the webservice. The IP we got points to the htdocs folder so my Web Service URL to create a new team is.
http://192.168.1.103/MyWebService/api/createteam.php
Testing our Web Service
Before moving to iOS Application Development we should first test the web service we created. For testing we can use any REST Client. I am using POSTMAN for chrome.
- Open POSTMAN and send a POST request with the required parameters to your service URL. You can see the below image for help.
- As you can see we got the success message. Now you can check you database table.
- Yes our URL is working fine. Now we will send a post request to the URL from our iPhone App to insert values. So lets move ahead to xcode side part.
Swift PHP MySQL Tutorial – Xcode Project
Creating a New Project
We have our web service now, lets start creating our iPhone App project in Xcode.
- Create a Single View App for iPhone in Xcode.
Adding Views
- Now go to your Main.storyboard and drag two Text Fields for name and member count values. You also need to add a Button where we will click to save the added values.
Connecting Views to ViewController
- Now connect the Views to your ViewController.swift file. So the code for your ViewController.swift will be.
// // ViewController.swift // SwiftPHPMySQL // // Created by Belal Khan on 12/08/16. // Copyright © 2016 Belal Khan. All rights reserved. // import UIKit class ViewController: UIViewController { //URL to our web service let URL_SAVE_TEAM = "http://192.168.1.103/MyWebService/api/createteam.php" //TextFields declarations @IBOutlet weak var textFieldName: UITextField! @IBOutlet weak var textFieldMember: UITextField! //Button action method @IBAction func buttonSave(sender: UIButton) { } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
- Now we will make a post request to your web service using NSMutableURLRequest.
Making POST Request to our Web Service
- Now inside the Button action function we will send a POST Request to the URL. For this we will use NSMutableURLRequest.
- So here is the code, I have written the comments to explain the code.
// // ViewController.swift // SwiftPHPMySQL // // Created by Belal Khan on 12/08/16. // Copyright © 2016 Belal Khan. All rights reserved. // import UIKit class ViewController: UIViewController { //URL to our web service let URL_SAVE_TEAM = "http://192.168.1.103/MyWebService/api/createteam.php" //TextFields declarations @IBOutlet weak var textFieldName: UITextField! @IBOutlet weak var textFieldMember: UITextField! //Button action method @IBAction func buttonSave(sender: UIButton) { //created NSURL let requestURL = NSURL(string: URL_SAVE_TEAM) //creating NSMutableURLRequest let request = NSMutableURLRequest(URL: requestURL!) //setting the method to post request.HTTPMethod = "POST" //getting values from text fields let teamName=textFieldName.text let memberCount = textFieldMember.text //creating the post parameter by concatenating the keys and values from text field let postParameters = "name="+teamName!+"&member="+memberCount!; //adding the parameters to request body request.HTTPBody = postParameters.dataUsingEncoding(NSUTF8StringEncoding) //creating a task to send the post request let task = NSURLSession.sharedSession().dataTaskWithRequest(request){ data, response, error in if error != nil{ print("error is \(error)") return; } //parsing the response do { //converting resonse to NSDictionary let myJSON = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary //parsing the json if let parseJSON = myJSON { //creating a string var msg : String! //getting the json response msg = parseJSON["message"] as! String? //printing the response print(msg) } } catch { print(error) } } //executing the task task.resume() } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
Making changes in Info.plist file
- Now the last important thing is you need to do some changes in your Info.plist file, because we are using Xampp and it is not a secure connection. And by default iPhone App will not allow you to make request on http URLs. So to make it work on http open Info.plist file and add the following at the end. Just before the </dict> tag.
<!-- add from here --> <key>NSAppTransportSecurity</key> <dict> <key>NSAllowsArbitraryLoads</key> <true/> <key>NSExceptionDomains</key> <dict> <key>yourdomain.com</key> <dict> <key>NSIncludesSubdomains</key> <true/> <key>NSThirdPartyExceptionRequiresForwardSecrecy</key> <false/> </dict> </dict> </dict> <!-- end of the code -->
- Now try running your application.
Testing Your Application
- Now the coding part is done. Just run your application in Simulator.
Swift PHP MySQL Tutorial
- Fill the values and click on Save Team. And then check Xcode.
Swift PHP MySQL Tutorial
- Yeah we got the success message. Now lets check the database.
Swift PHP MySQL Tutorial
Bingo! Its working absolutely fine. If you are having troubles you can get my source code from the link given below.
[sociallocker] Swift PHP MySQL Tutorial Source Code (1506 downloads) [/sociallocker]
So thats all for this Swift PHP MySQL Tutorial friends. Feel free to ask if having any doubts or queries with your comments. In the upcoming tutorials I will do some more cool things with Swift PHP MySQL, till then stay tuned. Thank You 🙂
How To Write A Simple Php/mysql Web Service For An Ios App
Source: https://www.simplifiedios.net/swift-php-mysql-tutorial/
Posted by: gilllind1944.blogspot.com
0 Response to "How To Write A Simple Php/mysql Web Service For An Ios App"
Post a Comment