Zizoo Zizoo - 3 months ago 8
Swift Question

How to handle JSON returned from HTTP GET request - Swift?

This is my code :

let myUrl = NSURL(string:"hostname/file.php");

let request = NSMutableURLRequest(URL:myUrl!);
request.HTTPMethod = "GET";


NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in

dispatch_async(dispatch_get_main_queue())
{



if(error != nil)
{
//Display an alert message

return
}



do {
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary

if let parseJSON = json { /* when the app reach here , will enter the catch and get out */

let userId = parseJSON["id"] as? String
print(userId)

if(userId != nil)
{

NSUserDefaults.standardUserDefaults().setObject(parseJSON["id"], forKey: "id")
NSUserDefaults.standardUserDefaults().setObject(parseJSON["name"], forKey: "name")

NSUserDefaults.standardUserDefaults().synchronize()


} else {
// display an alert message
print("error")

}

}
} catch
{
print(error)
}


}



}).resume()


my app getting the JSON from php file that parse the array from database into JSON and return it using
echo
and it return the following 2 rows :

[{"id":"1","name":"CIT","adminstrator_id":"1"},{"id":"2","name":"HelpDesk","adminstrator_id":"1"}]


When I print description of
json
I get
nil


I tried to cast the
json
to
NSArray
, when I print first
json[0]
I get the first row which is good but when I tried to cast result of
json[0]
to NSDictionary still I'll get nil from it

when the app reach the if statement
if let parseJSON = json
it will enter the catch and it's not printing any error , I don't know why ?

this my php code :

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydb";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM department";
$result = $conn->query($sql);
$rows = array();
if ($result->num_rows > 0) {
// output data of each row
while($r = $result->fetch_assoc()) {
$rows[] = $r;
}
$conn->close();
echo json_encode($rows);
} else {
$conn->close();
echo "0 results";
}
?>


So is the problem in my request or with handling the request ?

Answer

The JSON is an array of [String:String] dictionaries.

In a JSON string [] represents an array and {} represents a dictionary.

An URLRequest is not needed because GET is the default mode. .MutableContainers is not needed either because the values are only read.

Consider that the JSON returns multiple records. This code just prints all values for id and name.

let myUrl = NSURL(string:"hostname/file.php")!
NSURLSession.sharedSession().dataTaskWithURL(myUrl) { (data, response, error) in
  if error != nil {
    print(error!)
  } else {
    do {
      if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [[String:String]] {
        for entry in json {
          if let userId = entry["id"], name = entry["name"] {
            print(userId, name)
          }
        }
      } else {
        print("JSON is not an array of dictionaries")
      }
    } catch let error as NSError {
      print(error)
    }
  }
}.resume()
Comments