title: How to get JSON response in iOS? Getting nil value?
body: <p>I am sending data from an  php <code>api</code> to my ios application.</p>
  
  <p>having problem in getting the <code>JSON</code> response.</p>
  
  <p>this is the code which i tried to get the response.</p>
  
  <pre><code>@interface CPDScatterPlotViewController ()
  {
      NSURLConnection *conGet;
  }
  @end
  
  @implementation CPDScatterPlotViewController
  @synthesize responseData;
  
  
  - (void)viewDidLoad
  {
      [super viewDidLoad];
  
      NSLog(@"viewdidload");
       self.responseData = [NSMutableData data];
      NSURLRequest *request = [NSURLRequest requestWithURL:
                               [NSURL URLWithString:@"http://localhost/testApi/test_api.php?method=hello"]];
  
   conGet =[[NSURLConnection alloc] initWithRequest:request delegate:self];
  
      NSLog(@"Request sent");
  
      NSString* responseString = [[NSString alloc] initWithData:responseData encoding: NSUTF8StringEncoding] ;
  
      NSLog(@"Response String: %@", responseString);
      NSLog(@"val : %@ ", responseData);
  
  
  }
  
  
  - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
      NSLog(@"didReceiveResponse");
      [self.responseData setLength:0];
  }
  
  - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
      [self.responseData appendData:data];
  }
  
  - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
      NSLog(@"didFailWithError");
      NSLog([NSString stringWithFormat:@"Connection failed: %@", [error description]]);
  }
  
  - (void)connectionDidFinishLoading:(NSURLConnection *)connection {
      NSLog(@"connectionDidFinishLoading");
      NSLog(@"Succeeded! Received %d bytes of data",[self.responseData length]);
  
      // convert to JSON
      NSError *myError = nil;
      NSDictionary *res = [NSJSONSerialization JSONObjectWithData:self.responseData options:NSJSONReadingMutableLeaves error:&amp;myError];
  
      // show all values
      for(id key in res) {
  
          id value = [res objectForKey:key];
  
          NSString *keyAsString = (NSString *)key;
          NSString *valueAsString = (NSString *)value;
  
          NSLog(@"key: %@", keyAsString);
          NSLog(@"value: %@", valueAsString);
      }
  
      // extract specific value...
      NSArray *results = [res objectForKey:@"results"];
  
      for (NSDictionary *result in results) {
          NSString *icon = [result objectForKey:@"icon"];
          NSLog(@"icon: %@", icon);
      }
  
  }
  </code></pre>
  
  <p>But when i run this code i got the exception.</p>
  
  <p><code>Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'data parameter is nil'</code></p>
  
  <p>And this is my API file</p>
  
  <pre><code>&lt;?php&gt;
  function deliver_response($format, $api_response)
  {
  // Define HTTP responses
      $http_response_code = array(
          200 =&gt; 'OK',
          400 =&gt; 'Bad Request',
          401 =&gt; 'Unauthorized',
          403 =&gt; 'Forbidden',
          404 =&gt; 'Not Found'
      );
  // Set HTTP Response
      header('HTTP/1.1 ' . $api_response['status'] . ' ' . $http_response_code[$api_response['status']]);
  // Process different content types
      if (strcasecmp($format, 'json') == 0)
      {
  // Set HTTP Response Content Type
          header('Content-Type: application/json; charset=utf-8');
  // Format data into a JSON response
          $json_response = json_encode($api_response);
  // Deliver formatted data
          echo $json_response;
      }
      elseif (strcasecmp($format, 'xml') == 0)
      {
  // Set HTTP Response Content Type
          header('Content-Type: application/xml; charset=utf-8');
  // Format data into an XML response (This is only good at handling string data, not arrays)
          $xml_response = '&lt;?xml version="1.0" encoding="UTF-8"?&gt;' . "\n" .
                  '&lt;response&gt;' . "\n" .
                  "\t" . '&lt;code&gt;' . $api_response['code'] . '&lt;/code&gt;' . "\n" .
                  "\t" . '&lt;data&gt;' . $api_response['data'] . '&lt;/data&gt;' . "\n" .
                  '&lt;/response&gt;';
  // Deliver formatted data
          echo $xml_response;
      }
      else
      {
  // Set HTTP Response Content Type (This is only good at handling string data, not arrays)
          header('Content-Type: text/html; charset=utf-8');
  // Deliver formatted data
          echo $api_response['data'];
      }
  // End script process
      exit;
  }
  
  //////////My SQL Connection
  // Create connection
  $con = mysqli_connect("", "root", "", "test_db");
  
  // Check connection
  if (mysqli_connect_errno($con))
  {
      echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
  
  $result = mysqli_query($con, "SELECT count(*) FROM test_table");
  
  //$count = $result-&gt;num_rows;
  
  // Define whether an HTTPS connection is required
  $HTTPS_required = FALSE;
  // Define whether user authentication is required
  $authentication_required = FALSE;
  // Define API response codes and their related HTTP response
  $api_response_code = array(
      0 =&gt; array('HTTP Response' =&gt; 400, 'Message' =&gt; 'Unknown Error'),
      1 =&gt; array('HTTP Response' =&gt; 200, 'Message' =&gt; 'Success'),
      2 =&gt; array('HTTP Response' =&gt; 403, 'Message' =&gt; 'HTTPS Required'),
      3 =&gt; array('HTTP Response' =&gt; 401, 'Message' =&gt; 'Authentication Required'),
      4 =&gt; array('HTTP Response' =&gt; 401, 'Message' =&gt; 'Authentication Failed'),
      5 =&gt; array('HTTP Response' =&gt; 404, 'Message' =&gt; 'Invalid Request'),
      6 =&gt; array('HTTP Response' =&gt; 400, 'Message' =&gt; 'Invalid Response Format')
  );
  // Set default HTTP response of 'ok'
  $response['code'] = 0;
  $response['status'] = 404;
  $response['data'] = NULL;
  // --- Step 2: Authorization
  // Optionally require connections to be made via HTTPS
  if ($HTTPS_required &amp;&amp; $_SERVER['HTTPS'] != 'on')
  {
      $response['code'] = 2;
      $response['status'] = $api_response_code[$response['code']]['HTTP Response'];
      $response['data'] = $api_response_code[$response['code']]['Message'];
  
  
  // Return Response to browser. This will exit the script.
      deliver_response($_GET['format'], $response);
  }
  // Optionally require user authentication
  if ($authentication_required)
  {
  
      if (empty($_POST['username']) || empty($_POST['password']))
      {
          $response['code'] = 3;
          $response['status'] = $api_response_code[$response['code']]['HTTP Response'];
          $response['data'] = $api_response_code[$response['code']]['Message'];
      }
  // Return an error response if user fails authentication. This is a very simplistic example
  // that should be modified for security in a production environment
      elseif ($_POST['username'] != 'foo' &amp;&amp; $_POST['password'] != 'bar')
      {
          $response['code'] = 4;
          $response['status'] = $api_response_code[$response['code']]['HTTP Response'];
          $response['data'] = $api_response_code[$response['code']]['Message'];
      }
  }
  // --- Step 3: Process Request
  // Method A: Say Hello to the API
  //$_GET['method'] = 'hello';
  if (strcasecmp($_GET['method'], 'hello') == 0)
  {
      $response['code'] = 1;
      $response['status'] = $api_response_code[$response['code']]['HTTP Response'];
  
      $row = $result-&gt;fetch_row();
     // echo $row[0];
      $response['data'] = $row[0];   
  }
  // --- Step 4: Deliver Response
  // Return Response to browser
  deliver_response("json", $response);
  ?&gt;
  </code></pre>
  
  <p>If i run this Api it is showing the record on web-page that is 8346.</p>