【问题标题】:Data does not being sent to Database because it cannot be read数据没有被发送到数据库,因为它无法读取
【发布时间】:2018-02-22 11:52:30
【问题描述】:

我正在做一个项目,我需要将一些数据发送到远程数据库。所以我正在使用 Swift 3.1 开发一个 iOS 应用程序,当我尝试将数据发送到它说的数据库时,

The data couldn’t be read because it isn’t in the correct format.

还有一个错误;

Error Domain=NSCocoaErrorDomain Code=3840 "No value." UserInfo={NSDebugDescription=No value.}

这是我的快速代码:

let urlOfSMARTCF = URL(string: "http://192.168.1.99/insertData.php")
let request = NSMutableURLRequest(url: urlOfSMARTCF! as URL)
request.httpMethod="POST"
request.addValue("application/json", forHTTPHeaderField: "Accept")
for contact in contactsCaptuure
{
    let userMobileNumber = DBManager.shared.retriveRegisteredNumberOfMobile()
    let postParameters = "{\"usermobilenum\":\(String(describing: userMobileNumber!)),\"contactnum\":\(contact.phoneNumber!)}";
    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
        {
            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)
        }

    }
    print("Done")
    task.resume()
}

这是我在远程数据库中的 PHP:

<?php

if($_SERVER["REQUEST_METHOD"]=="POST")
{
require 'connectDB.php';
$userPhone = $_POST["usermobilenum"];
$contactNum = $_POST["contactnum"];
$query = "SELECT * FROM user WHERE UserMobNum='".$userPhone."'"; // Usermobile is registered.SIP exists.
if($results= mysqli_query($connect,$query))
{
    if(mysqli_num_rows($results)>0)
    {
        $i=0;
        while($rows=mysqli_fetch_assoc($results))
        {
            $sip[$i] = $rows["SIP"];
            $i++;
        }
        $queryToAddData = "INSERT INTO user (UserMobNum,SIP,Phone) VALUES ('".$userPhone."','".$sip[0]."','".$contactNum."')";
        if(mysqli_query($connect,$queryToAddData))
        {
            //Return success message to the app
                            echo "Success"
        }
        else
        {
            die(mysqli_error($connect));
        }
    }
    else
    {
        $availableSIP=false;
        while($availableSIP==false) // Assign a random value until it's being a valid one.
        {
            $sip[0]=rand(1,9999);
            $queryToCheck = "SELECT * FROM user WHERE SIP='".$sip[0]."'";
            if($results= mysqli_query($connect,$queryToCheck))
            {
                if(mysqli_num_rows($results)==0)
                {
                    $availableSIP=true;
                }
            }
        }
        $queryToAddData = "INSERT INTO user (UserMobNum,SIP,Phone) VALUES ('".$userPhone."','".$sip[0]."','".$contactNum."')";
        if(mysqli_query($connect,$queryToAddData))
        {
            //Return success message to the app
                            echo "Success"
        }
        else
        {
            die(mysqli_error($connect));
        }
    }
}
else
{
    echo "First Level Failure!";
    die(mysqli_error($connect));
}
mysqli_close($connect);
}
else
{
    echo "Failed in POST Method"
}

?>

我做了什么

查看了所有堆栈溢出和其他站点建议,但没有运气。我什至使用 json 验证器检查了我的 json 字符串,它通过了。这就是我的 json 字符串的样子。

{"usermobilenum":1234567890,"contactnum":9345}

但是,经过一番搜索,我发现这是因为远程数据库 PHP 发送了此错误消息。所以我检查了 PHP 中的每一个变量,但没有发现任何问题。这也不是 PHP 的问题,因为当我通过我的 android 应用程序连接时,我使用的是那些确切的 php 文件。这很好用。但在 iOS 中,它会产生该错误。有人可以帮帮我吗?

更新

这是 insertdataTest.php 文件:

<?php

if($_SERVER["REQUEST_METHOD"]=="POST")
{
    $userPhone = $_POST["usermobilenum"];
    echo $userPhone;
    mysqli_close($connect);
}
else
{
    echo json_encode("Failed in POST Method");
}

?>

【问题讨论】:

  • @ficuscr 试过了。运气不好
  • 其他代码中有什么?数据是否存储在数据库中?你还给json吗?你确定你没有在某处打印一些字符串吗?
  • @GabrieleCarbonai 我使用了一些打印功能来检查 swift 代码中的值。数据存储在 SQLite 数据库中,并通过 FMDB 库检索并转换为字符串。
  • 尝试通过浏览器打开创建json的文件,如果格式不正确会在浏览器中写入,然后你可以处理它

标签: php ios mysql json swift3


【解决方案1】:

{"usermobilenum":1234567890,"contactnum": 9345} - 这被视为字符串。这不是一个有效的 JSON。

更新代码:

let urlOfSMARTCF = URL(string: "http://192.168.1.99/insertData.php")
let request = NSMutableURLRequest(url: urlOfSMARTCF! as URL)
request.httpMethod="POST"
request.addValue("application/json", forHTTPHeaderField: "Accept")
for contact in contactsCaptuure {
let userMobileNumber = DBManager.shared.retriveRegisteredNumberOfMobile()

let postParameters = NSMutableDictionary()
postParameters["usermobilenum"] = userMobileNumber
postParameters["contactnum"] = contact.phoneNumber!

let jsonData = try? JSONSerialization.data(withJSONObject: postParameters, options: .prettyPrinted)
request.httpBody = jsonData

let task = URLSession.shared.dataTask(with: request as URLRequest) {
    data, response, error in

    if error != nil {
        print("error is \(String(describing: error))")
        return;
    }
    do {
        let myJSON = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? [String: Any]

        if let parseJSON: NSMutableDictionary = NSMutableDictionary(dictionary: myJSON as! NSMutableDictionary){

                let msg = parseJSON["message"] as! String
                print(msg)

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

}
print("Done")
task.resume()
}

【讨论】:

  • 我不认识。仍然得到这两个错误。 The data couldn’t be read because it isn’t in the correct format.Error Domain=NSCocoaErrorDomain Code=3840 "No value." UserInfo={NSDebugDescription=No value.}
  • @Sam94 在服务器端回显您请求的值。尝试回显 $userPhone 和 $contatcNum 并检查它从应用程序中获得了什么。
  • 我在我的问题中更新了完整的 PHP 代码。我确实在 Raspberry Pi 中运行远程服务器。在那里我找不到任何这样的输出。但我可以保证代码运行良好,因为 PHP 代码已经过多个测试数据的检查。
  • @Sam94 根据您的 php 代码,您没有向 API 调用发送任何响应。尝试进行编码响应并发送回应用程序。因为它等待服务器响应是成功还是失败。
  • 我做过一次。我确实使用了 json_encode 并在失败时回显每条消息。如果它通过了,它显然必须更新数据库对吗?无论如何,当我这样做时,它仍然没有在我的控制台上显示任何内容。只有这两个错误。
【解决方案2】:

伙计,我调试了你的代码,发现服务器响应有错误,而不是你的代码。试试这个,请尽快回复我

在这行之前“让 myJSON = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as?NSDictionary”

添加 "let str = String.init(data: data!, encoding: .utf8)

print(str ?? "error")"

请等一下。

【讨论】:

  • 这意味着您没有收到来自服务器的任何响应。请您的服务器人员对“echo json_encode”进行更改。那肯定有帮助。 :)
  • 我也添加了我的 PHP 代码。我的远程数据库是我的树莓派,我正在做一个项目。即使我对某些内容进行编码和回显,它仍然不会显示在我的控制台中。
  • 见死不救(mysqli_error($connect));没有什么要求在那里添加一些代码以进行输出。第 27 行和第 53 行。
  • 我在每个我希望终止连接的地方都做了 echo son_encode(mysqli_error($connect)) 错误。但它仍然什么也没显示。
  • 你能分享网址吗,我可以检查它或在浏览器上点击该网址并检查输出
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-08-15
  • 1970-01-01
  • 1970-01-01
  • 2021-12-18
  • 2016-10-15
  • 1970-01-01
相关资源
最近更新 更多