在JSON请求中没有来自服务器的响应

时间:2017-11-19 09:58:07

标签: php ios swift

我正在开发iOS应用程序的登录系统。

我现在正在测试来自远程服务器的响应。

这是应用程序中LOGIN按钮的功能:

   @IBAction func btnEntrar(_ sender: Any) {




        let correo = txtEmail.text!
        let pass = txtPassword.text!

        if(correo == "" || pass == ""){
            print("campos vacios")

            return
        }


        let postString = "email=\(correo)&password=\(pass)"

        print("envar solicitud \(postString)")


        let url = URL(string: "http://.../login.php")!
        var request = URLRequest(url: url)

        request.httpMethod = "POST"//tipo de envio -> metodo post
        request.httpBody = postString.data(using: .utf8)// concatenar mis variables con codificacion utf8

        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            guard let data = data else {//si existe un error se termina la funcion
                self.errorLabel.text = "error del servidor";

                print("solicitud fallida \(String(describing: error))")//manejamos el error
                return //rompemos el bloque de codigo
            }

            do {//creamos nuestro objeto json

                print("recibimos respuesta")



                if let json = try JSONSerialization.jsonObject(with: data) as? [String: String] {


                    DispatchQueue.main.async {//proceso principal

                        let mensaje = json["mensaje"]//constante
                        let mensaje_error = json["error_msg"]//constante
                        let error_int = Int(json["error_msg"]!)//constante
                        print("respuesta: \(mensaje_error ?? "sin mensaje")")

                    }
                }

            } catch let parseError {//manejamos el error
                print("error al parsear: \(parseError)")
                self.errorLabel.text = "error del servidor (json)";

                let responseString = String(data: data, encoding: .utf8)
                print("respuesta : \(String(describing: responseString))")
            }
        }
        task.resume()
    }

这是接收请求的PHP文件。

<?php
require_once 'include/DB_Functions.php';
$db = new DB_Functions();

// json response array
$response = array("error" => FALSE);


if (isset($_POST['email']) && isset($_POST['password'])) {

    // receiving the post params
    $email = $_POST['email'];
    $password = $_POST['password'];

    // get the user by email and password
    $user = $db->getUserByEmailAndPassword($email, $password);

    if ($user != false) {
        // use is found
        $response["error"] = FALSE;
        $response["uid"] = $user["unique_id"];
        $response["user"]["name"] = $user["name"];
        $response["user"]["email"] = $user["email"];
        $response["user"]["created_at"] = $user["created_at"];
        $response["user"]["updated_at"] = $user["updated_at"];
        $response["user"]["imagen"] = $user["imagen"];
        $response["user"]["nombre"] = $user["nombre"];
        $response["user"]["apellidos"] = $user["apellidos"];
        $response["user"]["nivel_usuario"] = $user["nivel_usuario"];
         $response["user"]["unidad"] = $user["unidad"];
        $response["user"]["id_usuario"] = $user["id_usuario"];

        echo json_encode($response);
    } else {
        // user is not found with the credentials
        $response["error"] = TRUE;
        $response["error_msg"] = "Wrong credentials! Please, try again!";
        echo json_encode($response);
    }
} else {
    // required post params is missing
    $response["error"] = TRUE;

    $response["error_msg"] = "Required parameters email or password is missing!";
    echo json_encode($response);
}
?>

我没有收到任何错误或异常,但我收到的最后一个输出是

print("recibimos respuesta")

我做错了吗?

修改

演示JSON输出

{"error":true,"error_msg":"Required parameters email or password is missing!"}

2 个答案:

答案 0 :(得分:1)

您的回复Object不仅包含String。它还包含Bool。你可以使用如下,

 if let json = try JSONSerialization.jsonObject(with: data) as? [String:Any] { //Any for, Any data type
    //Do with json
    print(json)
 }

答案 1 :(得分:0)

我认为你需要像这样(Objective-C)将请求的内容类型标题添加到:

[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
相关问题