Send HTTP POST Request example using Swift and PHP

In this example I am going to show you how to send an HTTP POST Request to a server side script written in PHP.

I have prepared a very simple PHP script that accepts two parameters, puts them into an array and outputs response in a JSON format.


// Read request parameters
$firstName= $_REQUEST["firstName"];
$lastName = $_REQUEST["lastName"];// Store values in an array
$returnValue = array("firstName"=>$firstName, "lastName"=>$lastName);// Send back request in JSON format
echo json_encode($returnValue); ?>

Now I am going to write Swift code that sends HTTP POST request and reads response body:

               let myUrl = URL(string: "");
        var request = URLRequest(url:myUrl!)
        request.httpMethod = "POST"// Compose a query string
        let postString = "firstName=James&lastName=Bond";
        request.httpBody = String.Encoding.utf8);
        let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
            if error != nil
            // You can print out response object
            print("response = \(response)")
            //Let's convert response sent from a server side script to a NSDictionary object:
            do {
                let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
                if let parseJSON = json {
                    // Now we can access value of First Name by its key
                    let firstNameValue = parseJSON["firstName"] as? String
                    print("firstNameValue: \(firstNameValue)")
            } catch {

Here is a video of how this code works.

I hope that this short Swift programming tutorial was helpful for you. There is some much more to learn about mobile apps development with Swift for iOS platform! Check the video courses below and may be one of them will be just what you need.