6

I'm trying to send a POST request with the Alarmofire library, but the request doesn't send the parameters properly.

My Code:

let parameters : Parameters = [
    "email": tfLoginEmail.text! as String,
    "password": tfLoginPassword.text! as String
]
Alamofire.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default).responseJSON{ response in
    //Some code that uses the response
}

The parameters variable has a count of 2 and both values are present, but the response to this request is an error about email and/or password being empty.

EDIT: My PHP:

/**
 * Account Login
 * url - /login
 * method - POST
 * params - email, password
 */
$app->post('/login', function() use ($app) {
            // check for required params
            verifyRequiredParams(array('email', 'password'));

            // reading post params
            $email = $app->request()->post('email');
            $password = $app->request()->post('password');
            $response = array();

            $db = new DbHandler();
            // check for correct email and password
            if ($db->checkLogin($email, $password)) {
                // get the user by email
                $account = $db->getAccountByEmail($email);

                if ($account != NULL) {
                    $response["error"] = false;
                    $response['id'] = $account['id'];
                    $response['name'] = $account['name'];
                    $response['email'] = $account['email'];
                } else {
                    // unknown error occurred
                    $response['error'] = true;
                    $response['message'] = "An error occurred. Please try again";
                }
            } else {
                // user credentials are wrong
                $response['error'] = true;
                $response['message'] = 'Login failed. Incorrect credentials';
            }
            echoRespnse(200, $response);
        }); 

I'd like to know what I'm doing wrong. Thanks in advance.

9
  • Can you add the server code with it ? Commented Dec 22, 2016 at 14:25
  • @ArnaudWurmel Sure, in a moment Commented Dec 22, 2016 at 14:26
  • @ArnaudWurmel Here you go, just added it Commented Dec 22, 2016 at 14:31
  • Do you need to send email and password in request body or as URL parameters? Commented Dec 22, 2016 at 14:32
  • 1
    try encoding: URLEncoding.httpBody instead of encoding: JSONEncoding.default and see if it helps. Commented Dec 22, 2016 at 14:42

1 Answer 1

10

Apparently the server expects the request body to be a URL-encoded string, not a JSON. Use encoding: URLEncoding.httpBody instead of encoding: JSONEncoding.default to fix this issue.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.