Simplified iOS

  • Home
  • About
  • Contact
  • Advertise
  • Write for Us

Swift PHP MySQL Tutorial – Connecting iOS App to MySQL Database

August 12, 2016 by Belal Khan 48 Comments

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.

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.

creating 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.

database

  • 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.

swift php tutorial

  • Create two more directories inside your project, as shown in the below image.

swift php

  • 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.

swift php mysql

  • 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.

xcode php mysql

  • As you can see we got the success message. Now you can check you database table.

swift php mysql tutorial

  • 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.

swift php mysql

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.

Swift PHP MySQL

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

Swift PHP MySQL Tutorial

  • Fill the values and click on Save Team. And then check Xcode.
swift php mysql tutorial

Swift PHP MySQL Tutorial

  • Yeah we got the success message. Now lets check the database.
Swift PHP MySQL Tutorial

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 (2293 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 🙂

Share this:

  • Tweet
  • Share on Tumblr
  • WhatsApp

Related

Filed Under: iOS Development Tutorial Tagged With: ios php mysql, swift php mysql, xcode connect to mysql database

About Belal Khan

I am Belal Khan, I am currently pursuing my MCA. In this blog I write tutorials and articles related to coding, app development, iphone etc.

Comments

  1. HS says

    September 1, 2016 at 3:35 pm

    I have error with this “Error Domain=NSCocoaErrorDomain Code=3840 “JSON text did not start with array or object and option to allow fragments not set.” UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}”

    Reply
  2. shihab says

    October 19, 2016 at 7:46 pm

    I have error with this “Error Domain=NSCocoaErrorDomain Code=3840 “JSON text did not start with array or object and option to allow fragments not set.” UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}”

    Reply
  3. Jack SI Bellis says

    October 20, 2016 at 2:41 pm

    Belal,
    Great tutorial. I particularly want to point out that it does something critical that, sadly, the majority of tutorials are getting wrong these days: it includes the barest minimum ingredients to perform the subject matter. When tutorials instead attempt to be “robust” or “realistic” they unintentionally hide the exact learning points that comprise the subject, and make a time-consuming puzzle out of things. There’s nothing wrong with making a robust example or tutorial (or even a more secure one)… but it then is no longer a tutorial of, in this case iOS>PHP>SQL… it is something different.

    I also suspect that this particular topic is a very valuable one, so it should be useful to a lot of people. There are only a very few end-to-end tutorials on iOS>db.
    Thanks

    Reply
  4. Jack SI Bellis says

    October 20, 2016 at 2:55 pm

    Some minor editing comments, mostly for newer folks, which most tutorial users are likely to be:

    -To use Postman, after pasting your url in the Post box, you have to use the Body ‘tab’ and enter the keys for your data.
    -The three interface controls need to be connected in the storyboard, not just the code shown in the view controller.
    -In the info.plist file replace yourdomain.com either your IP address or perhaps some variant of localhost. For me it worked with “193.01.12.7” or “localhost/” or “localhost\” or “localhost://” but hard to be sure if a value was cached.

    Reply
    • Mukta says

      March 17, 2017 at 5:26 pm

      how the 3 interface in storyboard will be connected? plz tell me.

      Reply
    • Micheal... says

      June 22, 2017 at 12:51 pm

      So I tried all of these. I did change your IP with mine of course. “The certificate for this server is invalid. You might be connecting to a server that is pretending to be “number” which could put your confidential information at risk.” Any guidance?

      Reply
  5. jaksa says

    December 5, 2016 at 9:51 am

    Why this method is not recommended..what should i change in oreder to make code more proffesional or secure?

    Reply
  6. Andy says

    February 7, 2017 at 7:33 pm

    Thanks for helping me as a beginner who can learn by doing quicker.

    I tried to compile all the codes you provide to get a feel, but ran into one single error in ViewController.swift shown below.

    Code –
    //creating NSMutableURLRequest
    let request = NSMutableURLRequest(URL : requestURL!)

    Error msg –
    ‘NSURL’ is not implicitly convertible to ‘URL’, did you mean to use ‘as’ to explicitly convert?

    BTW, I am using Xcode 8.2.1, MacOS 10.12.3. How should I fix it?

    It’d be very appreciated.

    using exact code an using Xcode 8.2.1 on MacOS 10.12.3,

    Reply
    • Jonathan says

      March 2, 2017 at 11:10 pm

      To get it working in Swift 3 do the following

      Change this
      //URL to our web service
      let URL_SAVE_TEAM = “http://192.168.1.103/MyWebService/api/createteam.php”

      To this
      //URL to our web service
      let URL_SAVE_TEAM = URL(string: “http://192.168.1.103/MyWebService/api/createteam.php”)

      Remove this line since it is no longer needed
      let requestURL = NSURL(string: URL_SAVE_TEAM)

      change this line
      //setting the method to post
      request.HTTPMethod = “POST”

      To this
      //setting the method to post
      request.httpMethod = “POST”

      Change this line
      //adding the parameters to request body
      request.HTTPBody = postParameters.dataUsingEncoding(NSUTF8StringEncoding)

      Tho this line
      //adding the parameters to request body
      request.httpBody = postParameters.data(using: String.Encoding.utf8)

      Change this line
      //creating a task to send the post request
      let task = NSURLSession.sharedSession().dataTaskWithRequest(request){
      data, response, error in

      To this
      //creating a task to send the post request
      let task = URLSession.shared.dataTask(with: request as URLRequest){
      data, response, error in

      Lastly Change This line

      //converting resonse to NSDictionary
      let myJSON = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary

      To this
      //converting resonse to NSDictionary
      let myJSON = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary

      Reply
      • Jonathan says

        March 11, 2017 at 11:48 pm

        One more thing needed is update the following line of code to match the URL we will be calling. Since we deleted the requestURL Variable we can call the URL Directly here.

        Change this line

        //creating NSMutableURLRequest
        let request = NSMutableURLRequest(url: requestURL!)

        To this

        //creating NSMutableURLRequest
        let request = NSMutableURLRequest(url: URL_SAVE_TEAM!)

        Reply
        • nany says

          August 3, 2017 at 10:35 am

          i’m using swift3 and i’ve some problem about code was written in swift2
          so , i wann ask u about URL?
          what did u meant ?
          how can i put URL?
          where i get it from?

          Reply
      • Reem says

        August 8, 2017 at 3:12 pm

        thanq for this helpful i realy cant even thank u again , when i’m convert like u i have probelm
        ;
        let myJSON = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary

        [the error : use unresolve identifier data]
        what i shoul do ?

        Reply
  7. Mário Santos says

    February 18, 2017 at 11:29 am

    Very good! Solved my problem. thanks
    How do I read and show for example the team lists?

    thanks

    Reply
  8. Brian says

    March 6, 2017 at 8:04 am

    Hi there
    Please assist

    The viewcontroller file does not run with swift3

    class ViewController: UIViewController {

    //URL to our web service
    let URL_SAVE_TEAM = URL(“string: http://192.168.56.1/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”
    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)
    request.httpBody = postParameters.data(using: String.Encoding.utf8)

    //creating a task to send the post request
    let task = URLSession.shared.dataTask(with: request as URLRequest){
    data, response, error in

    if error != nil{
    print(“error is \(error)”)
    return;
    }

    //parsing the response
    do {
    //converting resonse to NSDictionary
    let myJSON = try JSONSerialization.jsonObject(with: 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.
    }

    }

    They two lines that give me problems:
    This
    let URL_SAVE_TEAM = URL(“string: http://192.168.56.1/MyWebService/api/createteam.php“)

    AND
    This
    let request = NSMutableURLRequest(URL: requestURL!)

    Reply
    • Jonathan says

      March 11, 2017 at 11:45 pm

      Change

      //URL to our web service
      let URL_SAVE_TEAM = URL(“string: http://192.168.56.1/MyWebService/api/createteam.php“)

      to this

      let URL_SAVE_TEAM = URL(string: “http://192.168.56.1/MyWebService/api/createteam.php“)

      You had your apostrophe in the wrong place.

      That should fix the first problem.

      then change

      let request = NSMutableURLRequest(URL: requestURL!)

      to this

      let request = NSMutableURLRequest(URL: URL_SAVE_TEAM!)

      You need pass in the variable holding the URL because it needs a URL link to pass through into this method in order to make the HTTP request.

      Reply
  9. manpreet says

    March 9, 2017 at 7:48 am

    sir i am getting error in Createteam.php that name and member is undefined in line no 9 and 10

    Reply
    • ali says

      March 14, 2017 at 1:32 pm

      me to please give a solution

      Reply
      • Micheal... says

        June 22, 2017 at 12:53 pm

        Ok so I had the same error. This is what I got:
        https://stackoverflow.com/questions/4261133/php-notice-undefined-variable-notice-undefined-index-and-notice-undef

        Use the checked solution. Basically add the following in the createTeam.php:
        $teamName = isset($_POST[‘name’]) ? $_POST[‘name’] : ”;
        $teamName = !empty($_POST[‘name’]) ? $_POST[‘name’] : ”;

        $memberCount = isset($_POST[‘member’]) ? $_POST[‘member’] : ”;
        $memberCount = !empty($_POST[‘member’]) ? $_POST[‘member’] : ”;

        Reply
        • Steve says

          January 29, 2018 at 4:31 am

          I was getting the same error and fixed it using this code. I know get the success team created message but when I check my database the name is blank and the member is 0.

          It seems like it’s not getting the post string. Any ideas?

          Reply
          • David says

            April 14, 2018 at 2:58 pm

            There could be a mixed up with how you test the PHP. Tried $_GET instead of $_POST and see if it worked. I had the same problem initially and got the content after using the $_GET method instead.

  10. Luke says

    April 3, 2017 at 5:46 pm

    I am having an issue with 2 lines:

    let myJSON = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary

    Error = Consecutive statements on a line must be separated by ‘;’

    } catch {

    Error = Expected ‘while’ in ‘do-while’ loop

    Reply
  11. SIVA says

    April 14, 2017 at 3:25 pm

    Hi, i have use xcode 8.3.2 and while i import the url request it shows that error what i shared here, could you please help me to get out of this problem.
    ERROR: 1 ‘NSURL’ is not implicitly convertible to ‘URL’; did you mean to use ‘as’ to explicitly convert?

    ERROR: 2 ‘NSURLSession’ has been renamed to ‘URLSession’

    ERROR: 3 Editor placeholder in source file

    Reply
  12. Edwin says

    May 26, 2017 at 8:09 pm

    When I’m using the postman to check the database it give me an error when using the post. Says Undefined index: name in and Undefined index: member in the createteam.php

    Reply
    • Neeru says

      June 15, 2017 at 10:00 am

      yes same err !

      Reply
  13. Gustavo says

    May 28, 2017 at 7:15 pm

    Hi, I’m taking a message:
    Error Domain=NSCocoaErrorDomain Code=3840 “JSON text did not start with array or object and option to allow fragments not set.” UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}

    Reply
  14. Frank says

    May 29, 2017 at 8:03 pm

    I created another outlet to display the response on the UI. For some reason when the response is already received it take about 7 seconds for the message to display on the View Controller. Any idea why there’s a latency. The php server processed it fast. it the time from once the response mapped to the outlet label.

    //getting the json response
    msg = parseJSON[“message”] as! String?
    self.resp=msg
    //printing the response
    print(msg)
    self.outMsg.text = self.resp //< send response to label field in UI
    }

    Reply
  15. rich1812 says

    May 31, 2017 at 2:58 pm

    Hello, I only get to the php part. Instead of getting to the showed screen, on POSTMAN I keep getting this screen:http://www.mobwebplanet.com/phpWebService/mine.png
    Why is that? Looks like the $POST never got sent.

    Reply
  16. Newbe says

    June 6, 2017 at 7:25 am

    What if using mssqlserver as its database, can it?
    If you can, can you make the tutorial, thq

    Reply
  17. Dan says

    June 16, 2017 at 1:17 pm

    Very good tutorial – congratulations.

    Just one question that I couldn’t find the answer to is:

    How is this code to be secured ?? I mean – you do a webpost to a server without any checks on the server side (all credentials are stored on the server side)… Anyone can add items into the db… So – the following question rises – How can I make this secure enough to use it ?

    Thanks again,
    Best regards

    Reply
    • Belal Khan says

      June 16, 2017 at 3:27 pm

      You have to use some kind of authentication for server side. You can use a framework like laravel, lumen to build the REST Apis that provides the inbuilt authentication functionalities like OAuth, Basic Auth etc.

      Reply
      • Zeb says

        November 12, 2017 at 3:36 am

        Hello

        First I would like to say thank you for your amazing tutorials. If possible could you elaborate a bit more on integrating Larval, Lumen, Oauth or a Rest API? I’m building an app to communicate directly with my WP site and insert data in some tables and would like to secure my communications from app to server. I’ve googled searched but unfortunately come up short with a good guide or starting point for doing this. Again thank you and I appreciate any response you may have for a newbie.

        Reply
  18. Micheal says

    June 20, 2017 at 1:39 pm

    Well I keep getting an error of Not Authorized. Not sure what I am doing wrong. I am using MySQL Workbench…

    Reply
  19. Rich1812 says

    June 20, 2017 at 5:06 pm

    Although ther are some good tips in these tutorial. I don’t see the point of going through Postman. It adds an extra layer of and complexity and confusion, and it is neither iOS nor mySq related!

    Reply
  20. ahmad irfan says

    July 28, 2017 at 4:19 am

    hi!
    i have an error on this ={“error”:true,”message”:”Could not add team”}
    tell me why?

    Reply
    • Belal Khan says

      July 30, 2017 at 6:36 am

      The problem in your php scripts.. check them carefully

      Reply
  21. Fabio de Paula says

    August 3, 2017 at 4:54 pm

    Please Belal….

    Send a link with all the files, because we dont see the rest of code.

    Thank you so much.

    Reply
  22. Zeb says

    August 11, 2017 at 5:34 pm

    Hi Belal,

    Thank you so much for posting this tutorial. It is by far one of the best i’ve found. I’m a very green dev and am getting this error”{“error”:true,”message”:”You are not authorized”}” when using postman or browsing directly to the createteam.php file. I’m sure it is something simple and i’ve gone over my code multiple time but don’t see any errors. I see the error is originating from the else statement in createteam.php but i’m not whats causing it to error. I have looked in the apache2 log and no errors are thrown. I’m using Ubuntu LAMP server for web hosting if you could give me a few pointers or places I might look to resolve this I would greatly appriciate it.

    Thanks again for the great tutorial.
    Z

    Reply
    • Hitain Goyal says

      September 28, 2017 at 6:47 pm

      I’m getting the same error!!! Could you please help me in resolving this error!!!

      Thanks

      Reply
      • Giggione says

        April 9, 2018 at 6:25 pm

        you have to send a POST request not a GET

        Reply
  23. robson says

    November 20, 2017 at 10:52 pm

    {“error”:true,”message”:”You are not authorized”}

    Reply
  24. Z says

    November 26, 2017 at 10:51 pm

    I was able to resolve my error after going over the tutorial above. I missed the part about POSTMAN where it said to click on the “body” section and use it instead of the headers. After doing that the error went away, hopefully this will help someone else.

    Reply
  25. Amirhossein Aghajani says

    January 1, 2018 at 9:11 am

    thanks!
    how to show table from database in swift ?

    Reply
  26. mika says

    February 3, 2018 at 8:20 am

    hello,

    I have an issue with JSONSerialization :

    Error Domain=NSCocoaErrorDomain Code=3840 “No value.” UserInfo={NSDebugDescription=No value.}

    I don’t understand what it means. Could you help me please ? Thank you very much for this amazing tutorial !

    Reply
  27. nomac says

    February 19, 2018 at 4:42 pm

    Just xtra info — for the Newbies in Xcode: Connect the UI to Source Code see: https://developer.apple.com/library/content/referencelibrary/GettingStarted/DevelopiOSAppsSwift/ConnectTheUIToCode.html

    I have been struggling with the execution of the Swiftcode…

    This is a Cool Tutorial!!!

    Reply
  28. Diego says

    February 28, 2018 at 7:17 pm

    This is the code fully functional on Swift 4:

    import UIKit

    class ViewController: UIViewController {

    let URL_SAVE_TEAM = “http://192.168.1.64/MyWebService/api/createteam.php”

    @IBOutlet weak var textFieldName: UITextField!
    @IBOutlet weak var textFieldMember: UITextField!

    @IBAction func Login(_ sender: UIButton) {
    //created NSURL
    let requestURL = URL(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.data(using: String.Encoding.utf8)

    //creating a task to send the post request
    let task = URLSession.shared.dataTask(with: request as URLRequest) {
    data, response, error in

    if error != nil {
    print(“error is \(String(describing: error))”)
    return
    }

    do { //parsing the response
    let myJSON = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary //converting resonse to 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.
    }

    }

    Reply
    • masataka says

      May 26, 2018 at 9:25 am

      Thanks! I finally succeeded!

      Reply
  29. Chef Dennis Barimah says

    May 11, 2018 at 12:16 pm

    Hi Belal, please I have been able to insert into my MYSQL database and even fetch from the table, but my issue is I have a live server which I have hosted my apis the url works well when I use postman to test but I can’t use my iPhone 7 simulator to fetch from the live server. I always get connection lost in my log. Please any advice. Thanks

    Reply
  30. mike says

    July 24, 2018 at 6:06 pm

    thanks but i have to use $_GET instead of $_POST to make it works, do you have an idea why ?

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *




About Me

belal khan simplified ios

Hello I am Belal Khan, founder and owner of Simplified iOS. I am currently pursuing MCA from St. Xavier's College, Ranchi. Apart from my academic I am a blogger, I run various websites and majority of them are about coding and development.

Connect with Me

Follow Simplified iOS

Simplified iOS

Popular Posts

  • Swift SQLite Tutorial for Beginners – Using… (99,458)
  • Swift PHP MySQL Tutorial – Connecting iOS App… (98,347)
  • UIWebView Example to Load URL in iOS using Swift in Xcode (80,016)
  • Download Full High Sierra Installer to Create Bootable USB (70,345)
  • Xcode Login Screen Example using Swift 3, PHP and MySQL (67,312)
  • How to Format USB on Mac? Formatting External Hard… (61,391)
  • Swift JSON Tutorial – Fetching and Parsing… (59,413)
  • Firebase Realtime Database Tutorial for Swift using Xcode (53,721)
  • iOS Registration Form Example using PHP and MySQL (48,988)
  • Xcode Text Field Tutorial for iOS Application using Swift (41,226)




About

Simplified iOS is a blog where you can find latest tutorials related to coding and app development for iphone and MAC OS. Here you can get Simplified iPhone, iPad and Mac OS development tutorial to know the things about Apple Development from basics to advanced level.

Quick Links

  • Advertise
  • Contact
  • Disclaimer
  • Privacy Policy
  • Write for Us

Copyright © 2017 · Simplified iOS· All rights Reserved. And Our Sitemap.All Logos & Trademark Belongs To Their Respective Owners·