Zizoo Zizoo - 1 year ago 79
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


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


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

if(userId != nil)

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


} else {
// display an alert message


} catch



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


When I print description of
I get

I tried to cast the
, when I print first
I get the first row which is good but when I tried to cast result of
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 :

$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;
echo json_encode($rows);
} else {
echo "0 results";

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

Answer Source

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 {
  } 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 {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download