Php iOS URLSession Error“;JSON文本未以数组或对象开头,并且未设置允许片段的选项;

Php iOS URLSession Error“;JSON文本未以数组或对象开头,并且未设置允许片段的选项;,php,ios,json,swift,Php,Ios,Json,Swift,我目前在一个项目中,我必须向PHP文件提交一些数据,并从PHP获得返回 问题 当我尝试使用iOS URLSession执行此操作时,我得到了一个错误 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 f

我目前在一个项目中,我必须向PHP文件提交一些数据,并从PHP获得返回

问题

当我尝试使用iOS URLSession执行此操作时,我得到了一个错误

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.}
由于这个错误,我制作了一个示例php文件,其中返回了我从Swift发送的值。仍然会得到这个错误和一些额外的信息

<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)";
PHP:



我不知道这是什么原因。我曾试图在互联网上找到解决办法,但没有成功。请帮忙。我正在使用最新的Swift版本。

幸运的是,我找到了解决我自己问题的方法。我没能理解这个错误。正如它所说的“允许不设置片段的选项”,我所做的是添加
option.allowFragments
。那么整个线路在这个更换之后,

let myJSON = try  JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary
我可以解决这个问题并得到答案

当我的PHP文件中缺少分号时,我得到“JSON文本没有以数组或对象开头,并且允许不设置片段的选项”。调试需要使用浏览器完成,而不是从Xcode完成。
<?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");
}

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