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

标签 php ios swift

我正在为 iOS 应用开发登录系统。

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

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

   @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!"}

最佳答案

您的响应 Object 不仅包含 String。它还包含 Bool。你可以像下面这样使用,

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

关于php - 在 JSON 请求中没有来自服务器的响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47375594/

相关文章:

swift - 关闭 NSWindow 但不要将其置零

ios - 当变量为零时创建编译器错误

ios - 我可以对一个 UITableViewDelegate 使用多个 segues 吗?

iphone - Cocos2d 2.x、1.x 和 ARC

ios - 将 UIButton 添加到数组中

swift - 新用户注册时为 Parse 列设置默认值

PHP/MySQL - 比较 2 个不同数据库中的表

php - 强制通过 header 缓存动态生成的 JS/CSS 文件不适用于所有浏览器

php - 具有一对一关系的 Laravel 表单绑定(bind)

php - IN FIND_IN_SET 之间的 MySql 查询