数据未发送到数据库,因为无法读取数据

时间:2017-09-13 16:59:27

标签: php ios mysql json swift3

我正在处理一个项目,我需要将一些数据发送到远程数据库。所以我正在使用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");
}

?>

2 个答案:

答案 0 :(得分:0)

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

更新代码:

Local_Patient_Identifier    NHS_Number  GMP         Practice_Code_GP    StartDate  EndDate
------------------------    ----------  --------    ----------------    ---------- ----------
A111111111                  8BFD000     G111111     N77777              2016-05-23 2016-06-13
A111111111                  8BFD000     G222222     N77777              2016-06-13 2017-02-09
A111111111                  8BFD000     G3333333    ZZ44444             2017-02-09 NULL
A111111112                  8BFD002     G3333332    JJ44444             2015-05-21 2016-05-02
A111111112                  8BFD002     G3333332    KK44445             2016-05-02 2017-02-13
A111111112                  8BFD002     G3333332    WW44444             2017-02-13 NULL

答案 1 :(得分:0)

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

在此行之前“让myJSON =尝试使用JSONSerialization.jsonObject(带有:data!,options:.mutableContainers)作为?NSDictionary”

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

print(str ??“error”)“

我在等。