Search code examples
phpiosswiftpostalamofire

POST requests not working in Swift with Alamofire


I'm trying to send data from a Swift app to a backend in PHP. To test, I make a request via POST with Alamofire and print the request method as a response from the Server.

let URL_USER = "myurl"
var sampleRequest = URLRequest(url: URL(string: URL_USER)!)
sampleRequest.httpMethod = HTTPMethod.post.rawValue
            
AF.request(sampleRequest).uploadProgress{ progress in }.response(){
    response in
    if(response.data != nil) {
        print(String(bytes: response.data!, encoding: .utf8) as Any)
    }
    else {
        print("Error")
    }
}

The PHP script:

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    echo 'OK';
}
else {
    echo 'Wrong request method';
}

The server response is always Wrong request method

The same also occurs using the post parameter directly inside the Alamofire call, with this code:

AF.request("myurl", method: .post).response {...}

Any attempt to send the request via POST, even without Alamofire, fails and the server replies saying that the request is of type GET.

This occurs both on the simulator and on a real device, without any proxy.

The URL I call is based on https

UPDATE To test the basic functioning of Alamofire with the function of their documentation I tried this code:

AF.request(URL_USER, method: .post).response {
    response in
    if(response.data != nil) {
        print(String(bytes: response.data!, encoding: .utf8) as Any)
    }
    else {
        print("Error")
    }
}

But the response still goes Wrong request method and Proxyman says it's of type GET


Solution

  • The problem was caused by a redirect in the URL. For some reason https://mysite.tld was redirecting to https://www.mysite.tld using GET. In this way all the parameters and the type of request were altered. I solved the problem by making the request directly to https://www.mysite.tld. To find out the redirect I used Proxyman.