doubi6215 2017-01-23 11:48
浏览 66

swift服务器端说Xcode正在发送空数组

Xocde is sending email and password in JSON format to server side. But Server side PHP script says "Receiving empty array" .

 let parameters = ["name": NameTextField.text!, "password": passwordTextField.text!] as Dictionary<String, String>
let request = NSMutableURLRequest(url: NSURL(string: "api.php")! as URL)
    request.httpMethod = "POST"

    //create the session object
    let session = URLSession.shared

            do {
        request.httpBody = try  JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted) // pass dictionary to nsdata object and set it as request body

    } catch let error {
        print(error)
    }

    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")

    //create dataTask using the session object to send data to the server
    let task = session.dataTask(with: (request as NSMutableURLRequest) as URLRequest , completionHandler: { data, response , error in



        guard error == nil else {
            return
        }

        guard let data = data else {
            return
        }

        do {
            //create json object from data
            if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
             // Handling JSON
         }

Where am I going wrong? Is there any way to read from Xcode outgoing JSON ?

PHP Script: api.php

    require_once 'db.php';
    //creating response array
   $response = array();
   $conn = connect();


   if($conn)
   {
//Getting post values
  require_once 'getpflegerdata.php';

  //Get User ID
  $userid = getUserID($name, $password, $conn);
 //Überprüfung des Passworts
 if ($userid != '') 
 {
//Log In Table pfleger (api.php?loginpfleger)
if (isset($_GET['loginpfleger']))
{

  //1.Check if pfleger is looged in
  $loggedin = checkpflegerloggedin($userid,  $conn);
  if ($loggedin)
  {
    $response['error']=true;
    $response['message']='User is already logged in!';
  }
  else
  {
    //2.If not, insert pfleger
    //Inserting log in values
    if (insertpflegerdata($userid, $gps, $mac, $logintime, $logouttime, $conn))
    {
        $response['error']=false;
        $response['message']='Log Data added successfully';
      }
      else
      {
        $response['error']=true;
        $response['message']='Could not add log in data';
      }
    }

  }




}
else
{
    $response['error']=true;
    $response['message']= $test.'You are not authorized';
}
 }

else
{
        $response['error']=true;
        $response['message']='MySql connection Error';
}


echo json_encode($response);

?>

//getpflegerdata.php

<?php
   //JSON

if(isset($_POST['data']))
{
  $data = $_POST['data'];
  $json_a = json_decode($data, true);
  $name = $json_a['name'];
  $password = $json_a['password'];
  $gps = $json_a['gps'];
  if ($gps == '')
  {
    $gps = '0';
  }
  $mac = $json_a['mac'];
if ($mac == '')
  {
    $mac = '0';
  }
  if (isset($_GET['loginpfleger']))
  {
  $logintime = date("Y-m-d H:i:s");
  $logouttime = '1970-01-01 23:59:59';
  }
  if (isset($_GET['logoutpfleger']))
  {
  //Updating login time to 1970-01-01 23:59:59 does not make sense here
  $logintime = '';
  $logouttime = date("Y-m-d H:i:s");
  }
 }
else
{
  //No Username or Password will yield into an authentification error in api.php
  $username = '';
  $password = '';

}

db.php

<?php

function connect()
{
    require_once 'config.php';

    // Connecting to mysql database
    $conn = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);

    // Check for database connection error
    if (mysqli_connect_errno()) {
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }

    // returing connection 
    return $conn;
}



 //Function to insert log in data
    function insertpflegerdata($userid, $gps, $mac, $logintime, $logouttime, $conn)
    {
echo $userid.'<br>'; echo $gps.'<br>'; echo $mac.'<br>'; echo $logintime.'<br>'; echo $logouttime;
        $stmt = $conn->prepare("INSERT INTO DienstNachweisSanitas(userid, gps, mac, logintime, logouttime) values(?, ?, ?, ?, ?)");
        $stmt->bind_param("sssss", $userid, $gps, $mac, $logintime, $logouttime);
        $result = $stmt->execute();
        $stmt->close();
        if ($result) {
            return true;
        } else {
            return false;
        }
    }
//Function to update log out data
function updatepflegerdata($id, $logouttime, $conn)
{

    $stmt = $conn->prepare("UPDATE DienstNachweisSanitas SET logouttime=? WHERE id=?");
    $stmt->bind_param("si", $logouttime, $id);
    $result = $stmt->execute();
    $stmt->close();

    if ($result) {

        return true;
    } else {

        return false;
    }
}
//Check if pfleger is logged in
function checkpflegerloggedin($userid, $conn)
{
    $logouttimedefault = '1970-01-01 23:59:59';
    $stmt = $conn->prepare("SELECT id FROM DienstNachweisSanitas WHERE userid= ? and logouttime = ?");
    $stmt->bind_param("ss", $userid,  $logouttimedefault );

    if ($stmt->execute())
    {
      /* Store the result (to get properties) */
         $stmt->store_result();
         /* Get the number of rows */
         $num_of_rows = $stmt->num_rows;
         if ($num_of_rows > 0)
         {
           /* Bind the result to variables */
           $stmt->bind_result($iddb);
           while ($stmt->fetch())
           {
             $id = $iddb;
           }
         }
         else
         {
           $id = '';
         }

        return $id;

    }
    else
    {

        return false;
    }
    $stmt->close();
}

function getUserID($name, $password, $conn)
{

    $stmt = $conn->prepare("SELECT userid FROM RegistPflegerSanitas WHERE name = ? and password = ?");
    $stmt->bind_param("ss", $name, $password);

    if ($stmt->execute())
    {
        /* Store the result (to get properties) */
         $stmt->store_result();
         /* Get the number of rows */
         $num_of_rows = $stmt->num_rows;
         if ($num_of_rows > 0)
         {
           /* Bind the result to variables */
           $stmt->bind_result($iddb);
           while ($stmt->fetch())
           {
             $userid = $iddb;
           }
         }
         else
         {
           $userid = '';
         }
         return $userid;

    }
    else
    {

        return false;
    }
    $stmt->close();

}

?>

  • 写回答

1条回答 默认 最新

  • duangan4406 2017-01-23 11:52
    关注

    You have to read "RAW BODY":

    $json = file_get_contents('php://input');
    $data = json_decode($json, true);
    var_dump($data);
    
    评论

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条