Simplified iOS

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

Xcode JSON Example to Retrieve Data from MySQL using Swift

August 17, 2016 by Belal Khan 29 Comments

Hello friends today we will see an Xcode JSON Example. In last tutorial we learnt how we can save data from iOS App to our Web Server’s MySQL database. You can check the last tutorial from the below link.

Swift PHP MySQL Tutorial

It is really important that you go through the above given tutorial first, before moving ahead in this Xcode JSON Example. So if you have read the previous post you already inserted some data in your MySQL Database. Now the time to fetch the inserted data.

Lets start with creating the server side script. For the server side project I will be working on the same project we created in previous tutorial. So lets start.

Creating Server Side Scripts

First we need a script that will return all the data inserted in JSON format. If you don’t know about JSON then here is a brief definition for you.

What is JSON?

JSON is a light weight data interchange format. It helps our codes to parse or read the data. JSON stands for JavaScript Object Notation. You can read more about JSON from here.

Creating Web Service

So lets start creating our Web Service. Open the same project we created in last tutorial in PHP Storm.

  • First we will create a new function inside DbOperation.php file. So open your DbOperation.php inside includes directory and modify the code as follows.
<?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;
        }
    }

    //this method will return all the teams in the database
    public function getAllTeams(){
        $stmt = $this->conn->prepare("SELECT * FROM team");
        $stmt->execute();
        $result = $stmt->get_result();
        return $result;
    }

}
  • Inside the directory api create a new php file named getteams.php

xcode json example

  • Now inside the file getteams.php write the following php code
<?php

//including the file dboperation
require_once '../includes/DbOperation.php';

//creating a response array to store data
$response = array();

//creating a key in the response array to insert values
//this key will store an array iteself
$response['teams'] = array();

//creating object of class DbOperation
$db = new DbOperation();

//getting the teams using the function we created
$teams = $db->getAllTeams();

//looping through all the teams.
while($team = $teams->fetch_assoc()){
    //creating a temporary array
    $temp = array();

    //inserting the team in the temporary array
    $temp['id'] = $team['id'];
    $temp['name']=$team['name'];
    $temp['member']=$team['member'];

    //inserting the temporary array inside response
    array_push($response['teams'],$temp);
}

//displaying the array in json format
echo json_encode($response);

  • Now execute this script, and note down the URL, in my case the URL is http://192.168.43.207/MyWebService/api/getteams.php

xcode json example

So our Web Service is ready, as you can see we are getting a JSON String as a response. In Xcode side we will get this response and parse it. And this is how we communicate with an external web server. So lets move ahead in Xcode Side.

Xcode JSON Example to Retrieve Data from MySQL

We have our Web Service ready now lets create an Xcode Project to get and parse the response from our Web Service.

Creating an Xcode Project

  • Open Xcode and create a Single View App for iPhone.

xcode json example project

  • Now come inside ViewController.swift, and write the following code.
//
//  ViewController.swift
//  Xcode JSON Example
//
//  Created by Belal Khan on 17/08/16.
//  Copyright © 2016 Belal Khan. All rights reserved.
//

import UIKit

class ViewController: UIViewController {
    
    //Our web service url 
    let URL_GET_TEAMS:String = "http://192.168.43.207/MyWebService/api/getteams.php"
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        
        //created NSURL
        let requestURL = NSURL(string: URL_GET_TEAMS)
        
        
        //creating NSMutableURLRequest
        let request = NSMutableURLRequest(URL: requestURL!)
        
        //setting the method to post
        request.HTTPMethod = "GET"
        
        //creating a task to send the post request
        let task = NSURLSession.sharedSession().dataTaskWithRequest(request){
            data, response, error in
            
            //exiting if there is some error
            if error != nil{
                print("error is \(error)")
                return;
            }
            
            //parsing the response
            do {
                //converting resonse to NSDictionary
                var teamJSON: NSDictionary!
                teamJSON =  try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary
                
                //getting the JSON array teams from the response
                let teams: NSArray = teamJSON["teams"] as! NSArray
                
                //looping through all the json objects in the array teams
                for i in 0 ..< teams.count{
                    
                    //getting the data at each index
                    let teamId:Int = teams[i]["id"] as! Int!
                    let teamName:String = teams[i]["name"] as! String!
                    let teamMember:Int = teams[i]["member"] as! Int!
                    
                    //displaying the data
                    print("id -> ", teamId)
                    print("name -> ", teamName)
                    print("member -> ", teamMember)
                    print("===================")
                    print("")

                }
                
            } catch {
                print(error)
            }
        }
        //executing the task
        task.resume()
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

  •  As we are working with non secure URL http we need to add the following code in Info.plist file, the same as we did in the last tutorial.
<!-- 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 execute your application and you will see all the data retrieved in Xcode Output Console.
xcode json example

Xcode JSON Example

  • Bingo! It is working absolutely fine. Optionally you can display the retrieved data in some view.
  • And if you are having troubles then you can also download my source code from the link given below.

[sociallocker] Xcode JSON Example Project Download (969 downloads)  [/sociallocker]

So thats all for this Xcode JSON Example project. Feel free to ask your queries regarding this Xcode JSON Example, by commenting on this post. Thank You 🙂

Share this:

  • Tweet
  • Share on Tumblr
  • WhatsApp

Related

Filed Under: iOS Development Tutorial Tagged With: json parsing xcode swift, xcode ios tutorial, xcode json example

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. Mustafa says

    August 17, 2016 at 8:46 pm

    Hi Belal,

    For the majority of us who are on a shared hosting plan the the mysqlnd module may not be naively availble (even though Im using PHP 5.5). Due to the missing mysqlnd module I get the following error:

    Fatal error: Call to undefined method mysqli_stmt::get_result() in /home/domain/public_html/domain.com/ios/includes/DbOperation.php on line 35

    line 35 in DbOperation.php is as follows: $result = $stmt->get_result();

    Is there an alternative method we can use to retrieve the JSON data? Your Android tutorials use a different method it seems which work fine. But this IOS tutorial does not work if you dont have the module.

    Reply
    • Belal Khan says

      August 18, 2016 at 2:25 am

      In that case you can use other method of getting data from database. Use the same we did in the android tutorial. Or you can simply ask you hosting provider to add mysqlnd module.

      Reply
      • Mustafa says

        August 18, 2016 at 7:04 pm

        In that case your code above will need to change somewhat. Since the Android tutorial didn’t have a JSON response with an array title. Can you please show us how we can now display the JSON info to screen? preferably an example with displaying URL to image. Thank you.

        do {
        guard let teams = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSArray else {
        //Doesn’t exist, or isn’t an NSArray
        return
        }

        for team in teams {
        //getting the data at each index
        let teamId = team[“teamId”] as! String
        let teamName = team[“teamName”] as! String
        let teamMember = team[“teamMember”] as! Int

        //displaying the data
        print(“id -> “, teamId)
        print(“name -> “, teamName)
        print(“member -> “, teamMember)
        print(“===================”)
        print()
        }
        }
        //…

        Reply
  2. poorni says

    September 8, 2016 at 11:45 am

    Great tutorial..Thanks in advance…! Could you please tell me how delete json data in table view as this type?

    Reply
  3. Wajahat Hassan says

    September 22, 2016 at 4:31 pm

    thanks a lot this tutorial helps me a lot…. great and complete description to do this.

    Reply
  4. Raka Nugroho says

    September 24, 2016 at 3:54 pm

    for Swift 3 + XCode 8
    Permission

    NSAppTransportSecurity

    NSAllowsArbitraryLoads

    Reply
  5. Flavio says

    October 13, 2016 at 8:42 pm

    Great tutorial but i get errors when i get data:

    let teamId:String = teams[i][“giornata”] as! String! ==> Type ‘Any’ has no subscript members
    let teamName:String = teams[i][“name”] as! String! ==> Type ‘Any’ has no subscript members
    let teamMember:Int = teams[i][“member”] as! Int! ==> Type ‘Any’ has no subscript members

    Can you help me to understand how this problem can be solved?

    Reply
    • Melak says

      October 14, 2016 at 9:09 pm

      Did you figure this out yet? im having the same issue with Type ‘Any’ has no subscript members.

      Reply
    • tmb says

      November 6, 2016 at 4:14 pm

      Yup, I’m getting the same error – Any answers yet?

      Reply
      • McFly says

        November 30, 2016 at 6:52 am

        Any answers yet?

        Reply
    • John Nathan says

      October 19, 2017 at 3:39 am

      //getting the data at each index
      let teamId:Int = (teams[i] as! NSDictionary)[“id”] as! Int!
      let teamName:String = (teams[i] as! NSDictionary)[“name”] as! String!
      let teamMember:Int = (teams[i] as! NSDictionary)[“member”] as! Int!

      Reply
      • Noura says

        March 25, 2018 at 11:52 am

        It worked! Thank you

        Reply
  6. shamshir anees says

    October 15, 2016 at 8:30 pm

    Great tutorial ,
    how to use this for login page??

    thanks in advance..

    Reply
    • Belal Khan says

      October 16, 2016 at 2:09 pm

      I will post a tutorial for this soon

      Reply
  7. Anthony says

    December 5, 2016 at 1:49 pm

    I remark on the same problem as FLAVIO:

    Great tutorial but i get errors when i get data:

    Let teamId: String = teams [i] [“giornata”] as! String! ==> Type ‘Any’ has no subscript members
    Let teamName: String = teams [i] [“name”] as! String! ==> Type ‘Any’ has no subscript members
    Let teamMember: Int = teams [i] [“member”] as! Int! ==> Type ‘Any’ has no subscript members

    Can you help me to understand how this problem can be solved?

    I would really like to have a solution please

    Reply
    • Alexander says

      May 26, 2017 at 3:45 am

      Vc conseguiu resolver o problema Flavio?

      Reply
  8. vohoangtuit says

    December 16, 2016 at 4:45 pm

    My code with Swift 3, it OK

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

    //getting the JSON array teams from the response
    let data: NSArray = teamJSON[“data”] as! NSArray
    if let dataArr = data as? [[String: Any]] {
    for product in dataArr {
    //your code for accessing dd.
    let id:String = product[“id”] as! String
    let name:String = product[“name”] as! String
    let price:String = product[“price”] as! String
    let picture:String = product[“picture”] as! String

    let newProduct = Products(id: id,name: name,price: price,picture: picture,url: “”)

    self.product.append(newProduct)

    }

    Reply
  9. Joel says

    January 22, 2017 at 10:00 am

    How can you do this but not have the script accessible to anyone typing in the URL and getting all your data? Thanks

    Reply
    • Belal Khan says

      January 22, 2017 at 10:07 am

      The simplest solution is
      create a password and store it on your application and server as well
      Now while sending request send the password as well and in server side match the password if the password matches display the data else say it is an invalid access.

      the password is called api key

      For more information read about the OAuth Model for building REST APIs

      Reply
  10. Lucy says

    January 27, 2017 at 7:59 pm

    How would you go about editing existing information that is already in the database. Say I wanted to change the ‘Avengers’ member from 9 to 12?

    Reply
  11. Lucy says

    January 28, 2017 at 8:11 pm

    How would you go about editing the information, like if you wanted to change the Avengers member from ‘9’ to ‘1’?

    Reply
    • Belal Khan says

      January 30, 2017 at 12:13 pm

      You need to create another php script to handle the update. Then send the id of the row that is to be updated and the new value from ios side.

      Reply
  12. Yzd says

    March 13, 2017 at 10:07 am

    Hello Thank you for help i like this
    i want to add Viewcontrole Login and Password if the login and password correct open new viewcontroller
    how i can to do that i’m trying with your code but is give me erore
    Thank

    Reply
  13. Chrstine Kaplan says

    May 11, 2017 at 5:46 pm

    Your program doesn’t work as written and many people have asked you for help and your not responding.

    Reply
    • Belal Khan says

      May 23, 2017 at 4:24 pm

      Have you tried downloading my source code?

      Reply
  14. Marcus says

    June 3, 2017 at 10:07 pm

    How do we handle the SQL Query returns empty? I’m working on an iOS app that when using a retrieve via PHP on our web server, there will be times where it will return an empty array. How do I check the array to verify if its empty and handle the empty array without throwing an error?

    Reply
  15. BarryWhite says

    July 7, 2017 at 10:10 pm

    the following code fix’s the error

    func p2c() {
    //created RequestURL
    let get_codes:String = “http://192.168.20.20/api/getteams.php”

    let requestURL = URL(string: get_codes)

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

    //setting the method to GET
    request.httpMethod = “GET”

    //create a task to get results
    let task = URLSession.shared.dataTask(with: request as URLRequest) {
    data, response, error in

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

    //lets parse the response
    do {
    let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [String: Any]
    print(json)
    if let countries = json[“teams”] as? [[String: AnyObject]] {
    for country in countries {
    //print(“Country Name: \(country[“name”] as! String)”)
    //print(“Country Code: \(country[“code”] as! Int)”)
    if let couname = country[“name”] as? String {
    print(couname)
    }

    if let coucode = country[“member”] as? Int {
    print(coucode)
    }
    }
    }
    } catch {
    print(“Error Serializing JSON: \(error)”)
    }
    }
    //executing the task
    task.resume()

    }

    Reply
  16. Lun says

    August 18, 2017 at 9:16 am

    cannot work, the problem is
    Let teamId: String = teams [i] [“giornata”] as! String! ==> Type ‘Any’ has no subscript members
    Let teamName: String = teams [i] [“name”] as! String! ==> Type ‘Any’ has no subscript members
    Let teamMember: Int = teams [i] [“member”] as! Int! ==> Type ‘Any’ has no subscript members

    what the problem is? I am using Xcode 8.3.3

    Reply
    • Raymond says

      September 4, 2017 at 7:30 pm

      Here is a work around that I did

      let team1 = teams[i] as! NSDictionary // remind it is a NSDictionary and not ANy

      let teamId:Int = team1[“id”]! as! Int
      let teamName:String = team1[“name”]! as! String
      let teamMember:Int = team1[“member”]! as! Int

      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 PHP MySQL Tutorial – Connecting iOS App… (94,532)
  • Swift SQLite Tutorial for Beginners – Using… (94,175)
  • UIWebView Example to Load URL in iOS using Swift in Xcode (78,244)
  • Xcode Login Screen Example using Swift 3, PHP and MySQL (65,225)
  • Download Full High Sierra Installer to Create Bootable USB (61,246)
  • How to Format USB on Mac? Formatting External Hard… (60,779)
  • Swift JSON Tutorial – Fetching and Parsing… (58,674)
  • Firebase Realtime Database Tutorial for Swift using Xcode (52,001)
  • iOS Registration Form Example using PHP and MySQL (46,976)
  • Xcode Text Field Tutorial for iOS Application using Swift (39,039)




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·