Error Domain=NSCocoaErrorDomain Code=3840 AND

Hello, I have a problem when I launch the application I have this error displayed in the log of the swift:

Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not have any content around line 2, column 0." UserInfo={NSDebugDescription=JSON text did not have any content around line 2, column 0., NSJSONSerializationErrorIndex=1}

here is the php :

<?php
$hote="myHost";
$login="myLogin";
$mdp="myPassword";
$nomdb="nameDB";

// Create connection

$con= mysqli_connect($hote,$login,$mdp,$nomdb);
$con->set_charset("utf8mb4");
// Check connection
if (mysqli_connect_errno())
{
 echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

// This SQL statement selects ALL from the table 'Locations'
$sql = "SELECT `id`,`nom`,`prenom`,`tel`,`email`,`mdp`,`adr`,`cp`,`ville` FROM clients";
 
// Check if there are results
if ($result = mysqli_query($con, $sql))
{
  // If so, then create a results array and a temporary one
  // to hold the data
   
  $resultArray = array();
  $tempArray = array();
 
  // Loop through each row in the result set
  while($row = $result->fetch_object())
  {
    // Add each row into our results array
    $tempArray = $row;
    array_push($resultArray, $tempArray);
  }
 
  // Finally, encode the array to JSON and output the results
  echo utf8_encode($resultArray);
}
 
// Close connections
mysqli_close($con);
?>

With some research I know that this error is due to a json data received from the server (I don't know the exact term sorry)

but unfortunately finding the error and solving it are two different things could help me to solve it ?

Answered by Scott in 735669022

To debug this we would need to see the data received from the server before you try to parse it via JSONSerialization.

Is the line 1 bytes the output from calling print(data)? That would definitely not be the valid JSON you are looking for.

Now admittedly I have no experience with PHP, but I must wonder if this line does what the comment says it does:

// Finally, encode the array to JSON and output the results
echo utf8_encode($resultArray);

my bad i forgot my code :


import Foundation
import UIKit

protocol HomeModelDelegate {
   
  func itemsDowloaded(client:[Client] )
   
}
class HomeModel : NSObject {

  var delegate:HomeModelDelegate?
   
  func getItems(){
    //Hit the conn url
    let serviceURL = "http://myFTPSERVER/service.php"

    //Download the JSON Data
    let url = URL(string: serviceURL)
     
    if let url = url {
       
      // Create a URL Session
      let session = URLSession(configuration: .default)
       
      let task = session.dataTask(with: url) { (data, url, error) in
        
        if let data = data {
          //Succed
          print(data)
 
          //call the parseJson
          self.parseJson(data)
        }else{
           
        }
      }
      // Start the task
      task.resume()
    }
    //notify the view controller and pass the data back
     
  }
   
  func parseJson(_ data:Data){
     
    var clientArray = [Client]()
    do {
      //Parse the data into Client structs
      let jsonArray = try JSONSerialization.jsonObject(with: data, options: []) as! [Any]
      print(jsonArray)
       
      //loop through each result in the json array
      for jsonResult in jsonArray {
         
        //Cast json result as a dictionary
        let jsonDict = jsonResult as! [String:String]
       
         
        //Create a new client and set properties
        let cli = Client(id:jsonDict["id"]!,
                 lastName: jsonDict["nom"]!,
                 firstName: jsonDict["prenom"]!,
                 phone: jsonDict["tel"]!,
                 mdp: jsonDict["mdp"]!,
                 address: jsonDict["adr"]!,
                 cp: jsonDict["cp"]!,
                 city: jsonDict["ville"]!)
         
        clientArray.append(cli)
      }
       
      // Pass the client array back to delegation
      delegate?.itemsDowloaded(client: clientArray)
    }
    catch{
      print(error)
    }
  }
}

i also print my data i receive so here is the new log :

1 bytes
Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not have any content around line 2, column 0." UserInfo={NSDebugDescription=JSON text did not have any content around line 2, column 0., NSJSONSerializationErrorIndex=1}
Accepted Answer

To debug this we would need to see the data received from the server before you try to parse it via JSONSerialization.

Is the line 1 bytes the output from calling print(data)? That would definitely not be the valid JSON you are looking for.

Now admittedly I have no experience with PHP, but I must wonder if this line does what the comment says it does:

// Finally, encode the array to JSON and output the results
echo utf8_encode($resultArray);

yes 1 bytes is the print(data). then on i also created php pages that i send on my android studio app( same database) that i send in utf8

Not clear what you mean. Does the equivalent app on Android receive valid JSON when accessing the same URL (running the same PHP code)? Or is something else different? Or does the Android app also not receive valid JSON?

Can you access that URL via a web browser or a simple utility such as curl? What is the result?

it doesn't run on the same page php but i finally found the error and it was exactly what you thinks

echo utf8_encode($resultArray);

i try different encode and i found the good encode :

echo json_encode($resultArray);

thanks you you help me a lot !

Error Domain=NSCocoaErrorDomain Code=3840 AND
 
 
Q