Alamofire отсутствует параметры ответа при отправке почтового запроса - PullRequest
0 голосов
/ 03 мая 2018

Я пытаюсь использовать Alamofire для подключения к базе данных mysql для аутентификации пользователя.

Это код, который находится внутри моего метода действия кнопки входа в систему

    //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"
                }
            }
    }

когда я получаю ответ от сервера, я получаю это

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

Я также пытался использовать другой тип кодировки, такой как URLEncoding.default, но затем получил эту ошибку

FAILURE: responseSerializationFailed (Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed (Ошибка домена = NSCocoaErrorDomain Code = 3840 "Недопустимое значение вокруг символа 0." UserInfo = {NSDebugDescription = Недопустимое значение вокруг символа 0.}))

Вот так выглядит мой login.php

<?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;
    }
}
?>
...