How get the echo from PHP to Swift UIAlertController - php

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 !

Related

Error in Swift JSON when receiving 'json_encode' from PHP script. Works fine without it

I have a Swift function for a button that when pressed writes some details into a database via PHP:
#IBAction func createCommunityButtonTapped(_ sender: AnyObject) {
let communityName = communityNameTextField.text;
if (communityName!.isEmpty){
displayMyAlertMessage(userMessage: "You must name your Community");
return;
}else{
func generateRandomStringWithLength(length: Int) -> String {
var randomString = ""
let letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
for _ in 1...length {
let randomIndex = Int(arc4random_uniform(UInt32(letters.characters.count)))
let a = letters.index(letters.startIndex, offsetBy: randomIndex)
randomString += String(letters[a])
}
return randomString
}
let communityCode = generateRandomStringWithLength(length: 6)
passwordTextField.text = communityCode
let myUrl = URL(string: "http://www.quasisquest.uk/KeepScore/createCommunity.php?");
var request = URLRequest(url:myUrl!);
request.httpMethod = "POST";
let postString = "communityname=\(communityName!)&code=\(communityCode)&email=\(myEmail!)";
request.httpBody = postString.data(using: String.Encoding.utf8);
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
if (try! JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String:AnyObject]) != nil {
}
}
task.resume()
}
}
The function works great apart from whenever I add this echo jsonline into the PHP script:
if($newresult)
{
$returnValue["status"] = "Success";
$returnValue["message"] = "Community is registered";
echo json_encode($returnValue);
return;
}
Then I get an error Thread 8: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subside = 0x0) on this line:
if (try! JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String:AnyObject]) != nil {
}
And in the debug area the following details
data Data? some
response URLResponse? 0x0000618000223500
error Error? nil none
I think I'm missing a line, or need to set a variable to the JSONSerialization instead of 'try!' but I'm very unsure what.
You are returning null. Try this
if($newresult)
{
$returnValue["status"] = "Success";
$returnValue["message"] = "Community is registered";
return json_encode($returnValue);
}

JSON_encode causing error when returning an array from php script to Swift

In Xcode I am currently getting the following error:
Error Domain=NSCocoaErrorDomain Code=3840 "Garbage at end." UserInfo={NSDebugDescription=Garbage at end.}
This has just started happening when I added a function to my php script to retrieve 'community' details from the database. These details are stored in an array.
The following line echo json_encode($communities); appears to be causing the problem as it runs fine without it. Below is the full userLogin.php script. That line is at the bottom.
<?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;
}
$secure_password = md5($password);
$dao = new MySQLDao();
$dao->openConnection();
$userDetails = $dao->getUserDetailsWithPassword($email,$secure_password);
if(!empty($userDetails))
{
$returnValue["status"] = "Success";
$returnValue["message"] = "User is registered";
echo json_encode($userDetails);
}else{
$returnValue["status"] = "error";
$returnValue["message"] = "User is not found";
echo json_encode($returnValue);
}
//once logged in run function to get list of communities
$communities = array();
$communities = $dao->getCommunities($email);
echo json_encode($communities);
$dao -> closeConnection();
?>
I have tested the SQL function in the browser and it returns the correct values, output below:
[{"name":"EnclliffeT"},{"name":"OneWinner"},{"name":"Yesss"},{"name":"Treert"},{"name":"Westbrook"}]
I'm pretty sure then that the issue is with Swift not receiving the array properly.
This is the Swift code that runs when the user logs in, which gives the error:
#IBAction func loginButtonTapped(_ sender: AnyObject)
{
let userEmail = userEmailTextField.text;
let userPassword = userPasswordTextField.text;
if (userPassword!.isEmpty || userEmail!.isEmpty) { return; }
// send user data to server side
let myUrl = URL(string: "http://www.quasisquest.uk/KeepScore/userLogin.php");
var request = URLRequest(url:myUrl!);
request.httpMethod = "POST";
let postString = "email=\(userEmail!)&password=\(userPassword!)";
request.httpBody = postString.data(using: String.Encoding.utf8);
let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
DispatchQueue.main.async
{
if(error != nil)
{
//Display an alert message
let myAlert = UIAlertController(title: "Alert", message: error!.localizedDescription, preferredStyle: UIAlertControllerStyle.alert);
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler:nil)
myAlert.addAction(okAction);
self.present(myAlert, animated: true, completion: nil)
return
}
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String:AnyObject]
// retrieve login details and check to see if all ok
if let parseJSON = json {
let returnValue = parseJSON["status"] as? String
if(returnValue != "error")
{
self.delegate?.userLoggedIn(data: userEmail! )
UserDefaults.set(UserDefaults.standard)(true, forKey: "isUserLoggedIn");
self.dismiss(animated: true, completion: nil)
} else {
// display an alert message
let userMessage = parseJSON["message"] as? String
let myAlert = UIAlertController(title: "Alert", message: userMessage, preferredStyle: UIAlertControllerStyle.alert);
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler:nil)
myAlert.addAction(okAction);
self.present(myAlert, animated: true, completion: nil)
}
}
} catch
{
print(error)
}
}
}
task.resume()
}
You're outputting MULTIPLE json blocks, which is illegal json:
if(!empty($userDetails))
...
echo json_encode(...)
} else {
...
echo json_encode(...)
}
...
echo json_encode(...)
A block of JSON text can contain only one SINGLE json structure. Since you have two, you have a JSON syntax error.
e.g.
echo json_encode('hi');
echo json_encode('mom');
produces
"hi""mom"
And since JSON IS javascript code, you're basically trying to do this:
var foo = "hi""mom";
^--syntax error, unexpected string

Throwing out same response on login check PHP AND SWIFT

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()

using POST to store user information in web server IOS app

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

Http post request from Swift to a php script

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.

Categories