3

I'm currently on a project where I have to submit some data to PHP file and get the return from PHP.

Problem

When I try to do that using iOS URLSession, I'm getting an error,

The data couldn’t be read because it isn’t in the correct format.
Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set." 
UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}

Because of this error, I made a sample php file where I return the value which I sent from Swift. And still getting this error along with some additional information.

<NSHTTPURLResponse: 0x60400042e200> { URL: http://192.168.1.99/insertDataTest.php } { status code: 200, headers {
Connection = "Keep-Alive";
"Content-Length" = 5;
"Content-Type" = "application/json";
Date = "Thu, 07 Dec 2017 09:55:58 GMT";
"Keep-Alive" = "timeout=5, max=100";
Server = "Apache/2.4.10 (Raspbian)";

} }

What I've done so far

Here I know the content coming from the PHP, cannot be read by Swift. I'm sending a 5 digit string from Swift to PHP and since I'm returning it without doing anything, I'm getting length of 5 data. Also I manually added a code to php in orders to made header as application/json. But still getting this error. I'm sending json encoded data from PHP as well.

My Code

Swift:

let postParameters = "{\"usermobilenum\":12345}"
request.httpBody = postParameters.data(using: String.Encoding.utf8)
let task = URLSession.shared.dataTask(with: request as URLRequest)
{
    data, response, error in
    if error != nil
    {
      print("error is \(String(describing: error))")
      return;
    }

    do
    {
      print(response!)
      let myJSON = try  JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
      if let parseJSON = myJSON
      {
          var msg : String!
          msg = parseJSON["message"] as! String?
          print(msg)

      }
    }
    catch
    {
      print(error.localizedDescription)
      print(error)
    }

}
task.resume()

PHP :

<?php
header("Content-Type: application/json");
if($_SERVER["REQUEST_METHOD"]=="POST")
{
    $data =json_decode(file_get_contents('php://input'),true);
    $userPhone = $data["usermobilenum"];
    echo json_encode($userPhone);
    mysqli_close($connect);
}
else
{
    echo json_encode("Failed in POST Method");
}

?>

I have no idea what this causes. I did try to find a solution for this in the internet and had no luck. Please help here. I'm using the latest Swift version.

1 Answer 1

2

Luckily I found the solution for my own problem. I missed to understand the error. As it says "option to allow fragments not set.", What I did was adding option .allowFragments. So the whole line after this replacement,

let myJSON = try  JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary

And I could solve the problem and get the answer PHP returns.

Sign up to request clarification or add additional context in comments.

1 Comment

I get "JSON text did not start with array or object and option to allow fragments not set." when I am missing a semicolon in my PHP file. Debugging needed to be done using a browser, not from Xcode.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.