David David - 3 months ago 8
PHP Question

iOS: get response from PHP

I POST and GET data to/from my MySQL database with PHP. I want to get a response string.

For example:

A user wants to login in the app. Before storing the data and proceed I'll have to check if this username/password pair exists in my database.

@IBAction func login(sender: AnyObject) {
let request = NSMutableURLRequest(URL: NSURL(string: "http://example.com/checklogin.php")!)
request.HTTPMethod = "POST"
let postString = "username=\(username.text!)&password=\(password.text!)"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
}


This will POST username and password to this checklogin.php file:

<?php
$root = realpath($_SERVER["DOCUMENT_ROOT"]);
include "$root/config.php";

$username = $_POST['username'];
$password = $_POST['password'];

$statement = $pdo->prepare("SELECT * FROM contact WHERE username = :username AND password = :password");
$statement->execute(array('username' => $username, 'password' => $password));

$row = $statement->rowCount();

if ($row == 1) {
/* Send "true" to Xcode! */
}
else {
/* Send "false" to Xcode! */
}


This will check if the username/password pair exists.

I want to get a "true" or "false" response in iOS. If it's true user gets signed in. If it's "false" user gets an alert to check the login data.

What is the common way to send/get and handle responses like this? What is the common way achieve this?

Answer

You can not return the data to your app directly but there are several ways to send the data to app : The simple way is :

Use this on PHP to echo true or false and then

if ($row == 1) {
 echo "true";
}
else {
  echo "false";
}

Add this to get Response in your swift app and check if It's true or false with an if statement:

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 responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
    print("responseString = \(responseString)")
}
task.resume()

NOTE: Be aware that It's not a good way but the simple way as you said it's just an example...

If you want to get more data from the server use JSON

Comments