1

I'm trying to use Alamofire to connect to a mysql database for user authentication.

This is the code that is inside my login button action method

    //getting the username and password
    let params: Parameters = ["username":username.text!,"password":password.text!]

    //making a post request
    Alamofire.request(URL_USER_LOGIN, method: .post, parameters: params, encoding: JSONEncoding.default, headers: nil).responseJSON
        {
            response in
            //printing response
            print(response)

            //getting the json value from the server
            if let result = response.result.value {
                let jsonData = result as! NSDictionary

                //if there is no error
                if(!(jsonData.value(forKey: "error") as! Bool)){

                    //getting the user from response
                    let user = jsonData.value(forKey: "user") as! NSDictionary

                    //getting user values
                    let userId = user.value(forKey: "id") as! Int

                    //saving user values to defaults
                    self.defaultValues.set(userId, forKey: "userid")

                    //switching the screen
                    let TableView = self.storyboard?.instantiateViewController(withIdentifier: "TableView") as! TableView
                    self.navigationController?.pushViewController(TableView, animated: true)

                    self.dismiss(animated: false, completion: nil)
                }else{
                    //error message in case of invalid credential
                    self.labelMessage.text = "Invalid username or password"
                }
            }
    }

when i get a response from the server i get this

SUCCESS: {
    error = 1;
    message = "Parameters are missing";
}

I've also tried using a different type of encoding such as URLEncoding.default but then get this error

FAILURE: responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.}))

This is what my login.php looks like

<?php

    require_once 'dboperation.php';

    $response = array();

    if ($_SERVER['REQUEST_METHOD'] == 'POST') {

        if (isset($_POST['username']) && isset($_POST['password'])) {

            $db = new dboperation();

            if ($db->userLogin($_POST['username'], $_POST['password'])) {
                $response['error'] = false;
                $response['user'] = $db->getUserByUsername($_POST['username']);
            } else {
                $response['error'] = true;
                $response['message'] = 'Invalid username or password';
            }

        } else {
            $response['error'] = true;
            $response['message'] = 'Parameters are missing';
        }

    } else {
        $response['error'] = true;
        $response['message'] = "Request not allowed";
    }

    echo json_encode($response);
    ?>

dboperation.php

<?php
class dboperation

{
    private $conn;

    function __construct()
    {
        require_once 'Constants.php';
        require_once 'dbconnect.php';
        // opening db connection
        $db = new DbConnect();
        $this->conn = $db->connect();
    }

    /*
     * This method is added
     * We are taking username and password
     * and then verifying it from the database
     * */

    public function userLogin($username, $pass)
    {
        $stmt = $this->conn->prepare("SELECT idx, user_Id
                                    FROM Employee
                                    WHERE user_Id = ?
                                    AND user_Password = ?
                                    AND deleteYn = 'N'");
        $stmt->bind_param("ss", $username, $pass);
        $stmt->execute();
        $stmt->store_result();
        return $stmt->num_rows > 0;
    }

    /*
     * After the successful login we will call this method
     * this method will return the user data in an array
     * */


    public function getUserByUsername($username)
    {
        $stmt = $this->conn->prepare("SELECT user_Id FROM Employee WHERE user_Id = ? AND deleteYn = 'N'");
        $stmt->bind_param("s", $username);
        $stmt->execute();
        $stmt->bind_result($id);
        $stmt->fetch();
        $user = array();
        $user['id'] = $id;
        return $user;
    }

    private function isUserExist($username)
    {
        $stmt = $this->conn->prepare("SELECT user_Id FROM Employee WHERE user_Id = ? AND deleteYn = 'N'");
        $stmt->bind_param("sss", $username);
        $stmt->execute();
        $stmt->store_result();
        return $stmt->num_rows > 0;
    }


}
?>

dbconnect.php

<?php

class DbConnect
{
    private $conn;

    function __construct()
    {
    }

    /**
     * Establishing database connection
     * @return database connection handler
     */
    function connect()
    {
        require_once 'Constants.php';

        // Connecting to mysql database
        $this->conn = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);

        // Check for database connection error
        if (mysqli_connect_errno()) {
            echo "Failed to connect to MySQL: " . mysqli_connect_error();
        }

        // returing connection resource
        return $this->conn;
    }
}
?>
buttonSmasher96
  • 133
  • 1
  • 11
  • 1
    try adding `$response['debug'] = print_r($_REQUEST,true);` to see what is being sent to the server before passing the `$response` to `json_encode` – azjezz May 02 '18 at 22:29
  • 1
    Yeah, on your login.php code I'd dump `$_POST`. Looks like your username and password maybe come in both under another index like `['params' => {"username":"foo","password":"bar"}]` – ficuscr May 02 '18 at 22:31
  • Thanks you, I'll give these both a try. – buttonSmasher96 May 02 '18 at 22:43
  • I tried $response['debug'] = print_r($_REQUEST, true); and it gave this as output "Array\n(\n)\n"; – buttonSmasher96 May 03 '18 at 01:42
  • 1
    Check this link. https://stackoverflow.com/a/29970395/5710152 Instead of isset try !empty. if(!empty($_POST['username']) && !empty($_POST['password'])){ $username = $_POST['username']; $password = $_POST['password']; } – Boominadha Prakash M May 03 '18 at 04:47
  • I've been stuck for days and this still hasn't worked unfortunately. I get this response {"debug":"Array\n(\n)\n","error":true,"message":"Parameters are missing"} – buttonSmasher96 May 08 '18 at 00:38

0 Answers0