Swift login to json API

Viewed 1646

my API accepts the following JSON to login:

{ "operation" : "login", "user": { "name": "username", "password": "password" } }

In Xcode I already tried:

let username : String = textFieldUserName.text!
let password : String = textFieldPassword.text!

let param = "{ \"operation\" : \"login\", \"user\": { \"username\": \"" + username + "\", \"password\": \"" + password + "\" } }"
let dict = convertToDictionary(text: param)

//making a post request
Alamofire.request(URL_USER_LOGIN, method: .post, parameters: dict).responseJSON{
    response in
    //printing response
    print(response)
    print (param)
    //other handling removed
}

Function to convert to dictionary:

func convertToDictionary(text: String) -> [String: Any]? {
    if let data = text.data(using: .utf8) {
        do {
            return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
        } catch {
            print(error.localizedDescription)
        }
    }
    return nil
}

The Postman request is: POST to http://myserver/api/v1/logmein/login.php The request body is set to raw and contains: { "operation" : "login", "user": { "name": "username", "password": "password" } }

But the response from my API is always the error message for wrong parameters... If I paste the param from the console to Postman and fire a request, everything works fine.

Maybe someone could help me out?

2 Answers
Related