• 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 🙂