【问题标题】:iOS URLSession Error "JSON text did not start with array or object and option to allow fragments not set."iOS URLSession 错误“JSON 文本没有以数组或对象开头,并且允许未设置片段的选项。”
【发布时间】:2018-05-21 10:12:35
【问题描述】:

我目前正在进行一个项目,我必须将一些数据提交到 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 无法读取。 我正在从 Swift 向 PHP 发送一个 5 位字符串,因为我没有做任何事情就返回它,所以我得到了 5 个数据的长度。我还手动向 php 添加了一个代码,以便将标头制作为 application/json。但仍然收到此错误。我也在从 PHP 发送 json 编码数据。

我的代码

斯威夫特:

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");
}

?>

我不知道这是什么原因。我确实试图在互联网上找到解决方案,但没有运气。请在这里帮忙。我正在使用最新的 Swift 版本。

【问题讨论】:

    标签: php ios json swift


    【解决方案1】:

    幸运的是,我找到了解决自己问题的方法。我错过了理解错误。正如它所说的“允许未设置片段的选项。”,我所做的是添加option .allowFragments。所以这次替换后的整行,

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

    我可以解决问题并得到 PHP 返回的答案。

    【讨论】:

    • 我得到“JSON 文本没有以数组或对象开头,并且允许未设置片段的选项。”当我的 PHP 文件中缺少分号时。需要使用浏览器进行调试,而不是通过 Xcode。
    猜你喜欢
    • 2018-07-07
    • 1970-01-01
    • 2014-01-06
    • 1970-01-01
    • 2016-03-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-04
    相关资源
    最近更新 更多