POST Request on Swift does not work

1

Good morning, I looked for several sites a way to do a POST request for a server, found several ways and tried all of them, but none worked. I can receive the data from the page and even send GET variables in the URL, but POST variables are simply not sent.

func teste(){

    var request = NSMutableURLRequest(URL: NSURL(string: "http://minhaurl/efetuarLogin.php?variavel=teste&get=valor")!)

    var session = NSURLSession.sharedSession()

    request.HTTPMethod = "POST"

    var params = ["CPF":"00000000000", "senha":"12345678"] as Dictionary

    var err: NSError?

    request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &err)
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")

    var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in

        var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
        var err: NSError?

        var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error: &err) as NSDictionary

        if((err) != nil) {

            println(err!.localizedDescription)

        } else {

            println("JSON: \(json)")

        }

    })

    task.resume()

}

In the PHP page I try to access the variables through $ _POST, $ _GET and even $ _REQUEST, only GET variables are received on the server.

Can anyone tell me what may be going wrong? Thanks in advance.

    
asked by anonymous 12.03.2015 / 14:29

2 answers

1

Because the JSON header, and so on, do not expect to receive your CPF and password ) as $_POST['senha'] for example, since it was not a form that was sent.

You need to get the "body" of the request, which is a JSON , decode and then yes you will have the variables you need. On the server side, with PHP try something like this:

$inputJSON = file_get_contents('php://input');
$input = json_decode($inputJSON, TRUE);

// $input['CPF'], $input['senha']

No iOS is all correct. See if that solves your question.

    
12.03.2015 / 15:03
0

In the implementation you posted does not contain errors, it is just a very simple request.

Try removing the parameters from your URL in the request, as it may be being processed by the server and bypassing your httpBody.

    
12.03.2015 / 15:03