I am working on a login system for an iOS app.
I am now testing the response from remote server.
This is the function for the LOGIN button in the app:
#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()
}
And this the PHP file that is receiving the request.
<?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);
}
?>
I am not getting any error or exception, but the last output I receive is
print("recibimos respuesta")
Am I doing something wrong?
EDIT
Demo JSON output
{"error":true,"error_msg":"Required parameters email or password is missing!"}
Your response Object contains not only String. It contains Bool also. You could use like below,
if let json = try JSONSerialization.jsonObject(with: data) as? [String:Any] { //Any for, Any data type
//Do with json
print(json)
}
I think you need to add content type header to the request like this (Objective-C):
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
Related
It's almost a day since I'm working on my Login page of my App and I want to show to my app the errors (or whatever from the echo of PHP) to my xCode app. I'll show you my PHP file and my xCode
<?php
if($_SERVER['REQUEST_METHOD']=='POST')
{
$password = $_POST['password'];
$email = $_POST['email'];
if($password == '' || $email == '')
{
echo 'Please fill all values.';
}
else
{
require_once('GBconnect.php');
$sql = "SELECT * FROM Users WHERE email='$email' AND password='$password' OR mobile_no='$email' AND password='$password'";
$check = mysqli_fetch_array(mysqli_query($connection,$sql));
if(isset($check))
{
echo 'Login Success';
}
else
{
echo 'Email/Phone or Password is wrong.';
}
mysqli_close($connection);
}
}
else
{
echo 'error';
}
Here's my Swift file:
#IBAction func signUp(_ sender: Any)
{
let request = NSMutableURLRequest(url: NSURL(string: "http://34.205.37.201/restapi/GBlogin3.php")! as URL)
request.httpMethod = "POST"
let logEmail = "email=\(username.text!)&& password=\(password.text!)"
let logMobile = "mobile_no=\(username.text!)&& password=\(password.text!)"
if (username.text?.isEmpty)! || (password.text?.isEmpty)!
{
//display message
LoginInfoMyAlertMessage(userMessage: "Please input your Email or Phone and Password.");
}
if let checkNum = Int(username.text!)
{
print(checkNum)
request.httpBody = logMobile.data(using: String.Encoding.utf8)
}
let task = URLSession.shared.dataTask(with: request as URLRequest)
{
data, response, error in
if error != nil
{
print("error=\(String(describing: error))")
}
print("response = \(String(describing: response))")
let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
print("responseString = \(String(describing: responseString))")
}
task.resume()
username.text = ""
password.text = ""
return
A couple of things I see:
You specify logEmail but never use it anywhere
You have a space in logMobile but you should not when using application/x-www-form-urlencoded POST data
In a related item, you should use a more robust form encoding than concatenating strings.
You should use HTTP status codes to indicate success or failure, not strings. Use HTTP 200 for success, HTTP 401 for needing credentials, and HTTP 403 for invalid credentials
With all of that said, you haven't specified what you are seeing when you run the code. If you can do that, we can offer more specific advice. Use POSTMAN to verify that your server side works correctly, then you can ensure your client is working with the server.
You can encoding the response then unwrap in source app to handle the different messages.
<?php
$password = $_POST['password'];
$email = $_POST['email'];
if($password != '' || $email != ''){
$check = false; //Your connection
if($check){
echo json_encode([
"Message" => "Login Success",
"Status" => "Ok"
]);
}
else{
echo json_encode([
"Message" => "Email/Phone or Password is wrong.",
"Status" => "Error"
]);
}
}
?>
And then
#IBAction func signup(_ sender: Any) {
let request = NSMutableURLRequest(url: NSURL(string: "http://localhost:8888/chava/login.php")! as URL)
request.httpMethod = "POST"
let logEmail = "email=\(emial.text!) && password=\(password.text!)"
print(logEmail)
if (emial.text?.isEmpty)! || (password.text?.isEmpty)!{
print("Please input your Email or Phone and Password.");
}
request.httpBody = logEmail.data(using: String.Encoding.utf8)
let task = URLSession.shared.dataTask(with: request as URLRequest){
data, response, error in
if error != nil{
print("error=\(String(describing: error))")
}else{
//print(String(data:data!,encoding: .utf8) ?? "")
if let resp = data {
do{
let jsonResult = try JSONSerialization.jsonObject(with: resp) as! [String:AnyObject]
if let message = jsonResult["Message"]{
print(message)
}
}catch{
}
}
}
//print("response = \(String(describing: response))")
//let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
//print("responseString = \(String(describing: responseString))")
}
I hope help you !
I am trying to try and learn swift but want a backend server for php and need to convert the php to json to the app
Now what I want is to put email and password in the fields on app and it send a post request to the php server side and the php validates the details and sends back the response which will let me then decide what to do with the response.
I have managed to post to the server side with success I think but when I get the response back in the xcode it gives the same output weather the details are correct or in-correct,I have looked every where and followed tutorials but I keep getting the same problem I'm guessing its the way I am check details in the php file as I always get the error and not success.
Could someone help?
login.php
$email = addslashes(strip_tags($_POST['email']));
$password = addslashes(strip_tags($_POST['password']));
$password = md5($password);
$returnValue = array();
$sql = "SELECT email, user_password FROM `Accounts` WHERE `email` = '$email' AND user_password = '$password' LIMIT 1";
$fetchuser = mysqli_query($db_connect, $sql);
$row = mysqli_num_rows($fetchuser);
if($row = mysqli_num_rows($fetchuser) == 0){
$returnValue["status"] = "error";
$returnValue["message"] = "Account not found";
echo json_encode($returnValue);
} else {
$returnValue["status"] = "success";
$returnValue["message"] = "Account found";
echo json_encode($returnValue);
}
Swift Code
let userEmail = UserEmailTextField.text;
let userPassword = UserPasswordTextField.text;
if(userEmail!.isEmpty || userPassword!.isEmpty) { return; }
//SEND TO SERVER
let request = NSMutableURLRequest(URL: NSURL(string: "http://chaozsounds.com/chaozsounds/New-ChaozSounds/TeamChaozApp/register.php")!)
request.HTTPMethod = "POST"
let postString = "email=\(userEmail)&password=\(userPassword)"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
guard error == nil && data != nil else { // check for fundamental networking error
print("error=\(error)")
return
}
if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response!)")
}
let returnValue = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("returnValue = \(returnValue!)")
if(returnValue == "success") {
// LOGIN SUCCESSFUL
NSUserDefaults.standardUserDefaults().setBool(true, forKey:"isUserLoggedIn");
NSUserDefaults.standardUserDefaults().synchronize();
self.dismissViewControllerAnimated(true, completion: nil);
}
}
task.resume()
Ok so had to work around and I managed to do what I was after so will put code below
// Send post request
let request = NSMutableURLRequest(URL: NSURL(string: "urllinkhere")!);
request.HTTPMethod = "POST";
let postString = "email=\(userEmail!)&password=\(userPassword!)";
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);
// Get success or error
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
if error != nil {
print("no data found: \(error)")
return
}
if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response!)")
}
// this, on the other hand, can quite easily fail if there's a server error, so you definitely
// want to wrap this in `do`-`try`-`catch`:
do {
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary
if let parseJSON = json {
let returnValue = parseJSON["status"] as? String;
print("returnValue = \(returnValue!)")
if(returnValue == "success") {
// SUCCESS
NSUserDefaults.standardUserDefaults().setBool(true,forKey:"isUserLoggedIn");
NSUserDefaults.standardUserDefaults().synchronize();
self.dismissViewControllerAnimated(true, completion: nil);
}
}
} catch {
print(error)
}
}
task.resume()
I'm building an IOS app using Swift + xcode7 + php scripts + mysql server side (Bluehost) it is actually my first project using xcode
When I try to store user information into the database nothing happened and no error messages appear plus there is no row added.
Here is my code , I tried to inspect it but nothing seems to be wrong.
// send user data to a server side
let myUrl = NSURL(string: "http://thetogo.net/userRegister.php");
let request = NSMutableURLRequest(URL:myUrl!);
request.HTTPMethod = "POST";
let postString = "email=\(userEmail)&password=\(userPassword)";
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data,response, error in
if error != nil {
print("error=\(error)")
return
}
do {
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary
if let parseJSON = json{
let resultValue = parseJSON["status"] as? String
print("result: \(resultValue)")
var isUserRegistered:Bool = false;
if(resultValue=="Success") { isUserRegistered = true; }
var messageToDisplay:String = parseJSON["message"] as! String!;
if(!isUserRegistered){
messageToDisplay = parseJSON["message"] as! String!;
}
dispatch_async(dispatch_get_main_queue(), {
//DisplayAlertMessage with confirmation
let myAlert = UIAlertController(title: "Alert", message:messageToDisplay, preferredStyle: UIAlertControllerStyle.Alert);
let okAction = UIAlertAction(title: "Ok", style:UIAlertActionStyle.Default){ action in
self.dismissViewControllerAnimated(true, completion: nil);
}
myAlert.addAction(okAction);
self.presentViewController(myAlert, animated:true, completion: nil);
});
}} catch {
print(error)
}
}
And this is my php code
<?php
require("Conn.php");
require("MySQLDao.php");
$email = htmlentities($_POST["email"]);
$password = htmlentities($_POST["password"]);
$returnValue = array();
if(empty($email) || empty($password))
{
$returnValue["status"] = "error";
$returnValue["message"] = "Missing required field";
echo json_encode($returnValue);
return;
}
$dao = new MySQLDao();
$dao->openConnection();
$userDetails = $dao->getUserDetails($email);
if(!empty($userDetails))
{
$returnValue["status"] = "error";
$returnValue["message"] = "User already exists";
echo json_encode($returnValue);
return;
}
$secure_password = md5($password); // I do this, so that user password cannot be read even by me
$result = $dao->registerUser($email,$secure_password);
if($result)
{
$returnValue["status"] = "Success";
$returnValue["message"] = "User is registered";
echo json_encode($returnValue);
return;
}
$dao->closeConnection();
?>
1.) Write below code in your php code to check errors :
error_reporting(E_ALL | E_STRICT);
ini_set('display_errors', 'on');
2.) Use $_GET http method and hit url directly on browser.
After doing this you will see what error you are facing. After solving
error just replace $_GET to $_POST
I am trying to send a JSON object containing username and password info from an iOS app to my server for login. However, it seems like the php code never received the JSON object or decoded it correctly. I have tried many different ways to convert JSON object and send to server, but none of them succeeded. I am coding in swift 2 by the way. Any help? THANKS!
Here is my swift code:
let myUrl = NSURL(string: "myURL");
let request = NSMutableURLRequest(URL: myUrl!);
request.HTTPMethod = "POST";
let params : [String : AnyObject] = ["username": username!, "password": password!];
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type");
do {
let jsonData = try NSJSONSerialization.dataWithJSONObject(params, options: NSJSONWritingOptions());
request.HTTPBody = jsonData;
let jsonString = NSString(data: jsonData, encoding: NSUTF8StringEncoding)! as String
print(jsonString);
print(request.HTTPBody);
} catch {
print(error)
}
let task = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
do{
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableLeaves) as? NSDictionary
print(response)
if let parseJSON = json {
let resultValue = parseJSON["type"] as? Int
print("result: \(resultValue)")
}
} catch {
print(error)
}
})
task.resume()
And here is my php code:
require("Conn.php");
require("MySQLDao.php");
$fp = fopen("data.txt", "a+");
$data = file_get_contents('php://input');
$json = json_decode($data, false);
$username = $_POST['username'];
$password = $_POST['password'];
fwrite($fp, $data);
fwrite($fp, $json);
fwrite($fp, $username);
fwrite($fp, $password);
fclose($fp);
$returnValue = array();
if (empty($username) || empty($password)) {
$returnValue["status"] = "error";
$returnValue["message"] = "Missing required field";
echo json_encode($returnValue);
return;
}
$dao = new MySQLDao();
$dao->openConnection();
$userType = $dao->passwordAuthentification($username, $password);
if ($userType != null) {
$returnValue["type"] = (int)$userType;
echo json_encode($returnValue);
} else {
$returnValue["type"] = -1;
$returnValue["message"] = "user is not found";
echo json_encode($returnValue);
}
$dao->closeConnection();
I have a php script name UserRegister.php. In this script I have some Post variables. These variable comes from my iOS app and then the script should save it to my mysql database.
my .php script
require("Conn.php");
require("MySQLDao.php");
$name=htmlentities($_POST["name"]);
$email=htmlentities($_POST["email"]);
$password=htmlentities($_POST["password"]);
$returnValue = array();
if(empty($email) || empty($password))
{
$returnValue["status"] = "error";
$returnValue["message"] = "Missing required field";
echo json_encode($returnValue);
return;
}
$dao = new MySQLDao();
$dao->openConnection();
$userDetails = $dao->getUserDetails($email);
if(!empty($userDetails))
{
$returnValue["status"] = "error";
$returnValue["message"] = "User already exists";
echo json_encode($returnValue);
return;
}
$secure_password = md5($password);
$result = $dao->registerUser($name, $email, $secure_password);
if($result)
{
$returnValue["status"] = "Success";
$returnValue["message"] = "User is registered";
echo json_encode($returnValue);
return;
}
$dao->closeConnection();
my swift code
//Store data
//Send user data to server side
let myURL: NSURL! = NSURL(string: "http://localhost:8888/iOSDatabase/UserRegister.php")
let request: NSMutableURLRequest = NSMutableURLRequest(URL: myURL!)
request.HTTPMethod = "POST"
let postString = "name=" + UserName + "&email=" + UserEmail + "&password=" + UserPassword
println(postString)
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
println("response =\(response)")
if error != nil {
println("error=\(error)")
return
}
var responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
println("responseString =\(responseString)")
var err: NSError?
if var json: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers, error: &err) as? NSDictionary {
if error == nil
{
println(json)
}
}
}
task.resume()
I print out my response and get status code: 500 and in my header it says Connection = close. And it doesn't return any of the JSON file to my iOS app.
You are retrieving the variables using PHP's $_POST command but sending them using a GET request in Swift. You can change the request type in Swift using request.HTTPMethod = "GET" or alternatively use $_GET in PHP.