gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 15:12:47 24 4
gpt4 key购买 nike

我正在为 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com