Search code examples
phpiosobjective-cjsonjsonparser

Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0


enter image description herehere my RetriveData.Php:

<?php
ini_set("display_errors","on");
include("connection.php");

$query= "SELECT * FROM Person" ; //replace  with your table name
$result = mysqli_query($con,$query)  or  die("Error".mysqli_error($con));
//create an array
$json = array();
if(mysqli_num_rows($result))
{
  while($row=mysqli_fetch_row($result))
   {
      $json[]=$row;
   }
}
  echo json_encode($json);
 ?>

here id my .m file code :

NSError *error = nil;
NSString *url_string = [NSString stringWithFormat: @"http://127.0.0.1/RetriveData.php"];
NSData *data = [url_string dataUsingEncoding:NSUTF8StringEncoding];
NSMutableArray *json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
NSLog(@"%@",error);
NSLog(@"json: %@", json);

The problem is this json array print Null.


Solution

  • First, remove text "Successfully connect" in your PHP code. And the result is not in json format so far. Try to improve it.

    Second , at iOS side, you directly use url string as JSON. The right way is to get data from the url, and then convert it to JSON. Try:

    NSError *error = nil;
    NSString *url_string = @"http://127.0.0.1/RetriveData.php";
    NSURL *url = [NSURL URLWithString:url_string];
    if (url != nil) {
        NSData *data = [NSData dataWithContentsOfURL:url];
        NSMutableArray *json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
        NSLog(@"%@",error);
        NSLog(@"json: %@", json);
    }