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.
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
- 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
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.
- 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.
- 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 (1121 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 🙂
Mustafa says
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.
Belal Khan says
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.
Mustafa says
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()
}
}
//…
poorni says
Great tutorial..Thanks in advance…! Could you please tell me how delete json data in table view as this type?
Wajahat Hassan says
thanks a lot this tutorial helps me a lot…. great and complete description to do this.
Raka Nugroho says
for Swift 3 + XCode 8
Permission
NSAppTransportSecurity
NSAllowsArbitraryLoads
Flavio says
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?
Melak says
Did you figure this out yet? im having the same issue with Type ‘Any’ has no subscript members.
tmb says
Yup, I’m getting the same error – Any answers yet?
McFly says
Any answers yet?
John Nathan says
//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!
Noura says
It worked! Thank you
shamshir anees says
Great tutorial ,
how to use this for login page??
thanks in advance..
Belal Khan says
I will post a tutorial for this soon
Anthony says
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
Alexander says
Vc conseguiu resolver o problema Flavio?
vohoangtuit says
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)
}
Joel says
How can you do this but not have the script accessible to anyone typing in the URL and getting all your data? Thanks
Belal Khan says
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
Lucy says
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?
Lucy says
How would you go about editing the information, like if you wanted to change the Avengers member from ‘9’ to ‘1’?
Belal Khan says
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.
Yzd says
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
Chrstine Kaplan says
Your program doesn’t work as written and many people have asked you for help and your not responding.
Belal Khan says
Have you tried downloading my source code?
Marcus says
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?
BarryWhite says
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()
}
Lun says
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
Raymond says
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