Friday, 16 October 2015

IOS: Make an http request from the ios device using swift and also receiving a response as a json array from the server-side PHP Mysql

Hi developers, after a long research on the web i had finally ended up without getting an exact answer for my question "How to send request from ios swift to php and receive response as a json array". Anyway after a a lot of hardwork I had figured out how to do it in the simplest way.

First of all in the swift part we have 'request' variable which holds the URL of the respective php page to which we have to send the request; and the variable 'parameter' holds the value that has to be send to the server as a parameter. The 'nudges' variable holds the key "products" which is the json encoded array response. With the help of a for loop it extracts the respective value of the keys: item1, item2 and item3, and then prints it!

Secondly, we have three PHP web pages to manage the server-side, namely 'db_config.php' which holds database information, 'db_connect.php' which connects to the database and finally 'ios_get_all_items.php' which receives the request parameter from the device and performs MYSQL select operation and then returns the corresponding result in the form of a json array.


Swift:
func fetchData() {   
    var parameter = "AllItems"  
    var session = NSURLSession.sharedSession()   
    let request = NSMutableURLRequest(URL: NSURL(string: "http://mySampleWeb.com/ios_get_all_items.php")!)   
    request.HTTPMethod = "POST"   
    request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")   
    request.addValue("application/json", forHTTPHeaderField: "Accept")   
    let postString = "&category=\(parameter)"   
    request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)   
    var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in   
    // println("Response: \(response)")   
     var dataStr= NSString(data: data, encoding: NSUTF8StringEncoding)   
    // println("Body: \(dataStr)")   
     var err: NSError?   
     var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error: &err) as? NSDictionary   
     // printing the consol log if the JSONObjectWithData constructor return an error;   
     if(err != nil) {   
      println(err!.localizedDescription)   
      let jsonString = NSString(data: data, encoding: NSUTF8StringEncoding)   
      println("Error could not parse the response JSON: '\(jsonString)'")   
     }   
     else {     
      // checking for data in response json   
      if let parseJSON = json {   
       // Okay, the parsedJSON is here, let's get the value for 'success' out of it   
       var success = parseJSON["success"] as? Int   
       //   println("Succes: \(success)")   
       //   println("myMOB: \(mob)");   
       if(success==1){   
        self.deleteTableProduct();   
        //getting json array   
        let nudgesJSONResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! [String : AnyObject]   
        if let nudges = nudgesJSONResult["products"] as? [[String : String]] {   
         for nudge in nudges {   
 //recieving data : the value changes in every iteration  
          let item1= nudge["item1"]   
          println("Got item1: \(item1)")   
          let item2= nudge["item2"]   
          println("Got item2: \(item2)")   
          let item3= nudge["item3"]   
          println("Got item3: \(item3)")   
         }   
        }   
        //json array recieving completed   
         println("json array recieving completed  ")   

  }   
       else{   
        println("success failed value =\(success)")   
       }   
  }   
      else {   
       // If error occurs; problems such as server down.   
       let jsonString = NSString(data: data, encoding: NSUTF8StringEncoding)   
       println("Something went wrong. Error could not parse JSON: \(jsonString)")   
      }   
     }   
    })   
    task.resume()   
   }   



PHP:

*db_connect.php
 <?php  
 /*  
 we are connecting to the database using the information in db_config.php file  
 */  
 class DB_CONNECT {  
   function __construct() {  
     $this->connect();  
   }  
   function __destruct() {  
     $this->close();  
   }  
   function connect() {  
     require_once __DIR__ . '/db_config.php';  
     $con = mysql_connect(DB_SERVER, DB_USER, DB_PASSWORD) or die(mysql_error());  
     $db = mysql_select_db(DB_DATABASE) or die(mysql_error()) or die(mysql_error());  
     return $con;  
   }  
   function close() {  
     mysql_close();  
   }  
 }  
 ?>  

* db_config.php
 <?php  
 /*  
  * All database connection details  
  */  
 define('DB_USER', "root"); // your database username  
 define('DB_PASSWORD', "root"); // your database password  
 define('DB_DATABASE', "mydb"); // your database name  
 define('DB_SERVER', "localhost"); // your database server  
 ?>  


* ios_get_all_items.php
<?php 
/*  
  * Following code will list all the products  
  */  
 // array for JSON response  
 $response = array();  
 // include db connect class  
 require_once __DIR__ . '/db_connect.php';  
 // connecting to db  
 $db = new DB_CONNECT();  
 if(isset($_POST['category']))  
 {  
 $category= $_POST['category'];  
 }  
 // get all products from products table  
 $result = mysql_query("SELECT * FROM ITEMS where category='$category'") or die(mysql_error());  
 // check for empty result  
 if (mysql_num_rows($result) > 0) {  
   // looping through all results  
   // products node  
   $response["products"] = array();  
   while ($row = mysql_fetch_array($result)) {  
     // temp user array  
     $product = array();  
     $product["item1"] = $row["item1"];  
     $product["item2"] = $row["item2"];  
     $product["item3"] = $row["item3"];  
     // push single product into final response array  
     array_push($response["products"], $product);  
   }  
   // success  
   $response["success"] = 1;  
   // echoing JSON response  
   echo json_encode($response);  
 } else {  
   // no products found  
   $response["success"] = 0;  
   $response["message"] = "No products found";  
   // echo no users JSON  
   echo json_encode($response);  
 }  
 ?>  

Hope you enjoyed it! Don't forget to share the knowledge.

1 comment:

  1. Your article is extremely useful.Everyday your diary inspire ME nice deal} and helped to develop one thing new like I actually have developed a replacement app mobifriend
    : this is often great and pleasurable.Thanks for the awing posts , please keep updated often.

    ReplyDelete