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.

  

<?php
// 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: "http://www.swiftdeveloperblog.com/http-post-example-script/");
        
        var request = URLRequest(url:myUrl!)
        
        request.httpMethod = "POST"// Compose a query string
        
        let postString = "firstName=James&lastName=Bond";
        
        request.httpBody = postString.data(using: String.Encoding.utf8);
        
        let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
            
            if error != nil
            {
                print("error=\(error)")
                return
            }
            
            // 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 {
                print(error)
            }
        }
        task.resume()

Here is a video of how this code works.


Learn iOS Development with these Video Courses

The Complete iOS 11 & Swift Developer Course - Build 20 Apps

Use Xcode 9 & Swift 4 to make real apps like Uber and Instagram, with CoreML & ARKit. Includes AWS Credit and much more. Preview this video course. icon

How to Make a Freaking iPhone App - iOS 11 and Swift 4

iPhone App Development from scratch. Learn how to make iOS apps using Xcode 9. The Basics Include Pokemon Go & Snapchat. Learn to build iOS Apps with Xcode 9 and Swift 4. How to Make a Freaking iPhone App - iOS 11 and Swift 4 icon

iOS 11 and Xcode 9 - Complete Swift 4 & Objective-C Course

A Complete iOS 11 and Xcode 9 Course with Swift 4 & Objective-C. Preview this video course. iOS 11 and Xcode 9 - Complete Swift 4 & Objective-C Course icon
  • student

    Hi!

    I just tried running this code, but I got this message back from the responseString:

    responseString = Optional({“Message”:”Sorry, there was an error uploading your file.”,”Status”:”Error”,”userId”:null})

    firstNameValue: nil

    Do you know what the issue might be?

    • @disqus_p1NEqF1NA6:disqus can you make sure all parameters you are passing are not empty? like for example “userId”… also if you open the php page in the browser window and pass parameters via the uri string like this ?firstName=Sergey&lastName=Kargopolov&userId=1 what response message will you get?

  • Mike

    just solve it with same php code and swift :

    let link = “http://localhost/login/index3.php”
    let url = NSURL(string: link);
    let cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData
    let request = NSMutableURLRequest(URL: url!, cachePolicy: cachePolicy, timeoutInterval: 10.0)
    request.HTTPMethod = “POST”;
    // Compose a query string
    let postString = “firstName=James&lastName=Bond”;
    request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);
    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
    data, response, error in
    if error != nil
    {
    println(“error=(error)”)
    return
    }
    // You can print out response object
    println(“response = (response)”)
    // Print out response body
    let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
    println(“responseString = (responseString)”)
    //Let’s convert response sent from a server side script to a NSDictionary object:
    var err: NSError?
    var myJSON = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error:&err) as? NSDictionary
    if let parseJSON = myJSON {
    // Now we can access value of First Name by its key
    var firstNameValue = parseJSON[“firstName”] as? String
    println(“firstNameValue: (firstNameValue)”)
    }
    }

    task.resume()

    • Awesome Mike!

      • Toto

        Sir Mike,
        I Copied and Tried to run your code but same thing still happens, i still get this error(same error whit Sir Kargopolov’s code) :

        “error=Error Domain=NSURLErrorDomain Code=-1004 “Could not connect to the server.” UserInfo=0x7fcf94023d40 {NSUnderlyingError=0x7fcf9401a660 “The operation couldn’t be completed. (kCFErrorDomainCFNetwork error -1004.)”, NSErrorFailingURLStringKey=http://localhost/login/index3.php, NSErrorFailingURLKey=http://localhost/login/index3.php, _kCFStreamErrorDomainKey=1, _kCFStreamErrorCodeKey=61, NSLocalizedDescription=Could not connect to the server.}”

        can someone please help me with this?

  • Mathias Verhoeven

    Is there an example on how to do this in Swift 2?

    • what error message do you get? I can help you fix that.

      • serdar

        i get this error

        • Serdar, you need to add try and catch like this:

          do {
          let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary

          // YOUR CODE HERE

          } catch {
          print(error)
          }

          • serdar

            Thanks 🙂

  • Fergus Lo

    Nice video, i want to create a search function sending a search to my server and displaying it back to iOS in tableCell, wondering if u have any tutorials related on it, many thanks.

  • Olivier

    I get an error on this line:
    var myJSON = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error:&err) as? NSDictionary

    The error says “Extra argument ‘error’ in call” but I can’t find a solution.
    Can anybody help me please?

    • Oliver, try this:

      do {
      let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary

      // YOUR CODE HERE

      } catch {
      print(error)
      }

    • Ashwini

      Remove error:&err.Instead of this write following code:
      if error != nil
      {
      print(“Error(error)”)
      return
      }

  • ^J

    Hi there! I created a new project to test your code. It doesn’t have any errors and the output (in the logs / debug screen in xcode) is correct.

    My problem is, I’m trying to display it in the web page itself by using “echo” but I’m getting a null value. What’s the proper way on displaying it? Thank you in advance!

    • You are loading a php script from remote URL into your WebView and it prints our null instead of expected values? Have you tried passing request parameters to your PHP script using “GET” rather then POST? via the URL string like this http://www.yourwebsite.com/mypage.php?first_name=aaa&last_name=bbb

      • ^J

        I’m using your php code right now, and it returns like firstName=null. how can I display the “james”?

        • can you copy here the request url together with parameters you are sending to my script as GET Request?

          • Thierry Kosinski

            Hi. Thank you for this tutorial !
            I have the same problem than ^J. I’m using your scripts (php and xCode with the swift2 solution), I have no errors in the script and the output (in the debug area in xcode) seems correct, however on my website I’m getting null values ( {“firstName”:null,”lastName”:null} ).
            How can I display it ?
            (When I replace “POST” by “GET” it do not work, I obtain this error=Optional(Error Domain=NSURLErrorDomain Code=-1002 “unsupported URL while I have no errors with “POST”).
            Can you help me ?

  • Scott Brown

    I took your login course on udemy and it was excellent. Now I have an issue I’m able to parse one key from my php and it works but I get nil on the other (it’s not supposed to be nil). Any reason for this? Just to be clear the set up is similar to what you have above but is updated with swift 2.0 code with do try etc. I use print to see what has successfully parsed and as I said one string is successful but when I try with the other it doesn’t work. Btw this has nothing to do with your course. My login and sign up code works very well :).

    • Scott, it could be that the key name you use to read the value is different. For example there is a typo in the key name, or one of it’s characters is upper case and you typed it with a lower case… or may be that this key has indeed no value assigned to it..

  • adam

    this line
    let postString = “firstName=James&lastName=Bond”;

    can I send more than two variables. Im asking because i have expanded your login tutorial to add age, DOB etc. however I get error

    my code is:

    let postString = “email=(username)&password=(password)&firstName=(firstName)&lastName=(lastName)”

    • Yes, of course! You can pass on more request parameters. One thing thought, please make sure the values you pass are unwrapped or else they will be recorded wrapped into Optional(). You can unwrap the value of a variable by adding exclamation mark at the end. For example:
      let postString = “email=(username!)&password=(password!)&firstName=(firstName!)&lastName=(lastName!)”

      • adam

        thanks for the help however this is not working
        im am getting this error

        Error Domain=NSCocoaErrorDomain Code=3840 “No value.” UserInfo={NSDebugDescription=No value.}

        this is the swift code seen in image

      • Alex

        You made my day! I was searching for that error since 2 days. Your work is awesome!

  • Sami

    Dear Sergey,
    Thank you for the videos,
    I need your help desperately I am facing this error.

    Error Domain=NSCocoaErrorDomain Code=3840 “Garbage at end.” UserInfo={NSDebugDescription=Garbage at end.}

    attached is the code of json

    • ******** response data = Optional({“u201cfirstNameu201d”:”James”,”u201clastNameu201d”:”Bond”})
      firstNameValue: nil

      Why is firstNameValue nil?

      Here is my code:

      let myUrl = NSURL(string: “http://localhost/hello.php/”);

      let request = NSMutableURLRequest(URL:myUrl!);

      request.HTTPMethod = “POST”;

      // Compose a query string

      let postString = “firstName=James&lastName=Bond”;

      request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);

      let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {

      data, response, error in

      if error != nil

      {

      print(“error=(error)”)

      return

      }

      // You can print out response object

      print(“********** response = (response)”)

      // Print out response body

      let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)

      print(“******** response data = (responseString)”)

      //Let’s convert response sent from a server side script to a NSDictionary object:

      let json: NSDictionary?

      do {

      json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableLeaves) as? NSDictionary

      } catch _ {

      json = nil

      }

      if let parseJSON = json {

      // Now we can access value of First Name by its key

      let firstNameValue = parseJSON[“firstName”] as? String

      print(“firstNameValue: (firstNameValue)”)

      }

      }

      task.resume()

  • Maver1ck

    Hi Sergey,
    Thanks for your tutorial
    I have this error and I can’t manage to resolve it…

    A JSON parsing error occurred, here are the details:
    Error Domain=NSCocoaErrorDomain Code=3840 “No value.” UserInfo={NSDebugDescription=No value.}

    When I debug the error is happening at line 81, during the json constant initialization

    • Alex

      Hi,
      I had the same error. Check the php file for errors and if it´s really accesible. The error comes from the php file and not from swift code.

  • Vikash

    Hi Sergey,

    Thanks for your tutorial, I follow your youtube channels as well

    I’m noticing that after json serialization is done, my json variable is still nil. Do you know why this could be happening.

    Vikash

  • nguyễn thế phúc

    Thank for your tutorial, but I have problem below
    If in param value contain ‘&’ then code run not exactly, so how to fix it?

  • CafeAkf Themms

    hi Sergey, thanks for toturials.
    your Project working !
    my Project not working because my url not SSL. i’m adding parameters in to info.plist but not working.

    • After you have updated the .plist file. What error do you get? What exactly did you update your plist file with?

      • CafeAkf Themms

        hello Sergey, thank you for the answer. I solved the problem. Emanating from typographical errors in the database 🙂

  • Gopi Nath

    HIIII Nice Tutorial I Have Getting an Error in my code,

    response = Optional( { URL: http://localhost:3000/posttree } { status code: 400, headers {
    Connection = “keep-alive”;
    “Content-Length” = 989;
    “Content-Type” = “text/html; charset=utf-8”;
    Date = “Thu, 29 Sep 2016 13:56:04 GMT”;
    “X-Content-Type-Options” = nosniff;
    “X-Powered-By” = Express;
    } })

    Thanks in Advance

    • You are getting a Bad request HTTP code back. Server side script could not understand your HTTP request. Can you double check if all is good with it?

  • Brian Gibeault

    Thank you for the Tutorial – I have had no problems returning a one dimensional Array, but now I have been trying to return multi-dimensional Array with no success.

    Is there something different I need to do?

    • If the JSON response is an Array of other arrays or JSON objects then you will need to convert it to NSArray but if the response is JSON object that contains and Array which in its turn contains other array then you need to convert response to NSDictionary. What is the TOP level container of you JSON is it an array or a JSON? What is the very first character of you JSON response? Does it start with { or [

      • Brian Gibeault

        Thanks for getting back to me..
        so it starts with a [
        [{“id”:0,”FirstName”:”Bonnie”},{“id”:1,”FirstName”:”Brian”}……..

        I assume i have to somehow convert this from an array to a dictionary then to call individual components?

        I tried that and was able to return it as an NSArray.. of course then it is just a huge hunk of text 🙂

        • You need to convert this into NSArray this way:
          if let convertedJsonIntoArray = try JSONSerialization.jsonObject(with: data!, options: []) as? NSArray
          Check out this example I have which loads a list of images from a remote URL. List of images is loaded as a JSONArray of JSONObjects. Just like what you have.
          http://swiftdeveloperblog.com/code-examples/uicollectionview-load-list-of-images-from-remote-server-url/

          • Brian Gibeault

            Got it, thanks. I am going to review this and update my code. Thanks for the assist – I greatly appreciate it.

          • Brian Gibeault

            Thank you – took me a little bit but I have the data to populate the way I want it to now. Thanks for your help.

  • Andrés Carmona Ortíz

    Thanks for the tutorial!! I have a problem with the JSON that I send on the post, I need to send a parameter with a JSON Object inside something like this…. [ “var1″:”value”, “var2”: [“var1”:”value, “var2”:”value] ], so how can I send this URI format (var1=value&var2=?) have you used something like that? I tried using JSONSerialization but not working… thanks in advance!

  • okaner

    Thanks for the tutorial. I am coding on Xcode 8. Response contains only headers just below;

    Thanks in advance..

    response = Optional( { URL: http://www.innovs.com/inn-api/login } { status code: 200, headers {
    Connection = “Keep-Alive”;
    “Content-Encoding” = gzip;
    “Content-Length” = 231;
    “Content-Type” = “text/html”;
    Date = “Sun, 18 Dec 2016 18:50:15 GMT”;
    “Keep-Alive” = “timeout=5”;
    Server = “Apache/2.4.23”;
    Vary = “Accept-Encoding,User-Agent”;
    “X-Powered-By” = “PHP/5.4.45”;
    } })

  • Abdul Rafay

    What if we have dynamic variable as parameters like,

    let first = “James”
    let last = “Bond”
    And want to pass variables first, last in httpBody as,

    let postString = “firstName=(first)&lastName=(last)”;

    request.httpBody = postString.data(using: String.Encoding.utf8);

    Am not getting data if i do as above

  • Ali Uzunoğlu

    Hi,
    Thanks for the tutorial. I have a problem I am using autolayout with this and I am getting something like this:

    2017-02-24 18:48:07.602 httpRequest[2027:368883] This application is modifying the autolayout engine from a background thread, which can lead to engine corruption and weird crashes. This will cause an exception in a future release.

    Stack:(

    0 CoreFoundation 0x222ef933 + 150

    1 libobjc.A.dylib 0x21a8ae17 objc_exception_throw + 38

    2 CoreFoundation 0x222ef861 + 0

    3 Foundation 0x22be13e7 + 170

    4 Foundation 0x22be1273 + 38

    5 Foundation 0x22a8a1db + 42

    6 Foundation 0x22a85e63 + 362

    7 UIKit 0x2697137d + 52

    8 UIKit 0x26971d63 + 222

    9 UIKit 0x270ae23f + 322

    10 UIKit 0x26b700e1 + 148

    11 UIKit 0x26866a73 + 714

    12 QuartzCore 0x248febcd + 128

    13 QuartzCore 0x248fa375 + 348

    14 QuartzCore 0x248fa209 + 16

    15 QuartzCore 0x248f96d1 + 368

    16 QuartzCore 0x248f93a5 + 520

    17 QuartzCore 0x24926ecb + 310

    18 libsystem_pthread.dylib 0x2202254d + 508

    19 libsystem_pthread.dylib 0x2202214f + 86

    20 libsystem_pthread.dylib 0x22021b3d _pthread_wqthread + 1044

    21 libsystem_pthread.dylib 0x22021718 start_wqthread + 8

    )

    So, I need to convert my task to async task but how can I do this?

    Thanks

  • Tony Franzis

    Hai ,
    how to post the following xml formatt in xcode8 with swift 3

    {

    “logdata”: {

    “Email”: “tony@gmail.com”,

    “Password”: “asd”,

    “type”: “agent”

    }

    }

    • To send this json you will need to send “http post” request. Json will need to be in http request body.

      • Tony Franzis

        Hi,
        thank you, I have an another problem. I want to get response in my console with doing following xml data with my api

        tony@gmail.comasdagent
        I think the php server will only get the data in xml format,i need to find how to parse the xml in swift 3 plz help me

  • Viper

    what i am trying to do is that to get the value from the two textfields and convert those two fields into son format and send that JSON to the server receive.php
    how do i create a JSON & passed the data on button click