php - iOS URLSession 错误 "JSON text did not start with array or object and option to allow fragments not set."

标签 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 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 添加了一个代码,以便将 header 制作为 application/json。但仍然收到此错误。我也从 PHP 发送 json 编码的数据。

我的代码

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

?>

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

最佳答案

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

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

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

关于php - iOS URLSession 错误 "JSON text did not start with array or object and option to allow fragments not set.",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47692774/

相关文章:

java - jackson 在序列化时不包含字段的类型信息

javascript - 无法在 React 中访问嵌套的 JSON 对象

objective-c - 在 iOS 上,有没有更快的方法来获取 mainBundle 资源的 URL?

php - 用户 co_p 已经有超过 'max_user_connections' 个事件连接

php - 在 PHP 中使用 MySQL 类的简单范围问题

php - 如何使用 LIKE 语句创建 PDO 参数化查询?

ios - Mapbox 清除路线折线

ios - 如何将图像上传到服务器

java - 如何将一种 JSON 模式映射到另一种模式?

php - 如何从一对多关系中使用 SQL 获取平均税率