Php JSON请求中没有来自服务器的响应
我正在为iOS应用程序开发登录系统 我现在正在测试来自远程服务器的响应 这是应用程序中登录按钮的功能:Php JSON请求中没有来自服务器的响应,php,ios,swift,Php,Ios,Swift,我正在为iOS应用程序开发登录系统 我现在正在测试来自远程服务器的响应 这是应用程序中登录按钮的功能: @IBAction func btnEntrar(_ sender: Any) { let correo = txtEmail.text! let pass = txtPassword.text! if(correo == "" || pass == ""){ print("campos vacios")
@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);
}
?>
我做错什么了吗
编辑
演示JSON输出
{"error":true,"error_msg":"Required parameters email or password is missing!"}
我认为您需要向请求添加内容类型标题,如下所示(Objective-C):
您的响应
对象
不仅包含字符串
。它还包含Bool
。你可以像下面这样使用
if let json = try JSONSerialization.jsonObject(with: data) as? [String:Any] { //Any for, Any data type
//Do with json
print(json)
}
因为响应数据不是JSON格式,或者JSON格式不是[String:String]。如果您毫不犹豫地提供url或使用demo JSON输出更新问题。@RAJAMOHAN-S,我已使用demo JSON输出更新了我的问题的空白参数。我的解决方案将根据问题正文数据不是JSON来工作。但看起来服务器需要一些带有电子邮件和密码的字典,而不是像“email=(correo)”这样的字符串&password=(pass)“查看PHP代码bro
if(isset($\u POST['email'])和&isset($\u POST['password']){}
RAJAMOHAN-S的答案有效。感谢您的努力。
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
if let json = try JSONSerialization.jsonObject(with: data) as? [String:Any] { //Any for, Any data type
//Do with json
print(json)
}