• Widmarc Thomas

    I am getting “result: Optional(“error”)”. Plus the IOS Simulator showed “User is not found”. Does the name of the database matter? That’s the only part I could not fulfill.

    • @thomaswid:disqus yes, the name if the database, user name and the password all these details are important. Your script will not be able to connect to your database and communicate with it if one of these is not correct. Please make sure connection details are correct and you can successfully connect to a database from your php script.

  • Widmarc Thomas

    Disregard last error post, I forgot to change links to the PHP files, It’s working now like Butter! lol…

    • Awesome!!! I am, very happy it worked for you! 🙂

      • Adalid Garcia

        Kargopolov can you share us the code to download?

  • Tian Xie

    can you put code on github.com, thanks

  • Conor

    Hey, I was curious about the link to your page visible in the //send user data to server side// portion of the code visible at 11:21 in the video. What exactly does that link to, and what will be my counterpart to that? Will it just be the userRegister.php that I made using your template?

    • Hi Conor! Thank you for your message! The link in my example is pointing to my php script on my server and it works with a database installed on my server. For your application you will need to have your own server, your own database and this link should be pointing to a script hosted on your server. For example: conor.com/users/userRegister.php.

      • Conor

        Alright, I’ve got one of those, but I’m running into some confusion figured out what the exact URL to the file is. Do you know any tricks that can give me that?

        • 🙂 no Conor, there are no tricks I know that have to do with the URL to your server.

          1. You need to have a domain name which points to your server. For example, “conor.com”
          2. Your server will have a folder which contains web site folders and files. Lets assume you have a folder called “scripts”. Or you can call it differently “api-scripts”
          3. You need to create and put your registerUser.php script into that “scripts” folder.
          4. Now you should be able to access your registerUser.php by http://www.conor.com/scripts/registerUser.php
          5. Use this URL to send HTTP Post requests to.

          Hope this helps

          • Conor

            I have the server, but it’s part of my school’s server structure and I’m having trouble pinning down the exact url. When I try to create the account in the simulator I get an error that “error=Error Domain=NSURLErrorDomain Code=-1003 “The operation couldn’t be completed. (NSURLErrorDomain error -1003.)” UserInfo=0x799250c0 {NSErrorFailingURLStringKey=http://www.burrow.soic.indiana.edu/u/team3/cgi-pub/userRegister.php, _kCFStreamErrorCodeKey=8, NSErrorFailingURLKey=http://www.burrow.soic.indiana.edu/u/team3/cgi-pub/userRegister.php, _kCFStreamErrorDomainKey=12, NSUnderlyingError=0x7873ea10 “The operation couldn’t be completed. (kCFErrorDomainCFNetwork error -1003.)”}”

            Am I at least correct in assuming this indicates my URL is incorrect?

          • It looks like the URL is not correct. I have tried accessing it via the browser window and it says that the page is not found: http://burrow.soic.indiana.edu/u/team3/cgi-pub/userRegister.php

          • Conor

            I seem to have almost everything working, but I’m running into an issue where it goes to the desired page regardless of whether or not the login information is correct, even with the self.dismissViewControllerAnimated line in the “Success” conditional. I have made sure I have no other segues or dismissals of the LoginViewController anywhere in the code. Any ides what could be happening here?

          • do you have any code in your AppDelegation didFinishLaunchingWithOptions function?

  • Manoj

    When I try signup it stores in my database but response is not showing up in the app that “user is registered” but when I replace the URL with your URL it works fine! Please tell me how can I resolve this issue!!!!!!

    • @disqus_P49whDzft3:disqus if you access the login.php from your browser will it give you any errors? Will it print anything at all? For example try opening your script in browser window login.php?email=&password=

      • Manoj

        when I open userLogin.php in my browser window its says “{“status”:”error”,”message”:”Missing required field”}”

  • Tsaraboulidis Agis

    How i can create this database help me plz. thank you @kargopolov:disqus

  • karin khera

    Hey Kargo

    Great tutorial. I was able to register new user however when i want to check if user exist the sql query is not working right. I took out the where clause and the function is able to count all the rows in the table. How ever when i add in the where clause it doesn’t return a result. Do you know what is the cause of the is. I tried many different way to add in the variables to the query.

    Thanks

    • @karin khera try printing out values in where clause. It sounds like they do not match anything in the database. If you run sql query manually or hard code correct values into where clause does it return correct result?

    • Adalid Garcia

      @karinkhera:disqus it works for you?

      • karin khera

        Yes it did. Turns out there the single quotes was the problem.

        • Adalid Garcia

          i did all on video but it doesnt save on database ,it doesnt display any error , can you share me the code of xcode?

          • karin khera

            My xcode code is pretty much the same as Kargo. But here is a sample of my sql statement. If you look at the single quote at my table name they are different from the one you type in from the keyboard. ( keyboard input -> ‘table name’)
            $getUserIDSQL = “SELECT * FROM `ItemBrand` WHERE user_id='” . $userName . “‘”;

            Also one of my mistake i did was, i was using php echo which messed the JSON format when Xcode receives the result.

            Hope this helps

  • Alan

    Could you please upload the required files to the github.com?

  • mengran li

    Hello,

    Could you perhaps upload the scrips on pastebin? I’m not familiar with PHP and apparently when I copy-paste the MySQLDao.php in Sublime it shows that the lower half is commented. I think it all starts with $sql = “select * from users where user_email=’” . $email . “‘”;

  • Senty

    Hi, I cannot connect to database from php files. I am getting an error even when trying to establish connection to database:
    exception ‘Exception’ with message ‘Could not establish connection with database’ in /root/blinddate/MySQLDao.php:21 Stack trace: #0 /root/blinddate/script.php(15): MySQLDao->openConnection() #1 {main}

    I opened a question on StackOverflow but I couldn’t find an answer yet. Any ideas how to resolve this issue? StackOverflow Question Link (Issue Resolved)

  • Senty

    I tried to adapt this to Facebook Login and used this code:

    I am getting:
    Parse error: syntax error, unexpected ‘,’, expecting ‘&’ or variable (T_VARIABLE) in /root/blinddate/MySQLDao.php on line 67

    Chunk of code:
    public function registerUser($Facebookid, $firstname, $lastname, $FBpictureURL, $Gender, $UserEmail)
    {
    $sql = “insert into Users set FacebookId=?, firstname=?, lastname=?, FBpictureURL=?, Gender=?, UserEmail=?”;
    $statement = $this->conn->prepare($sql); // Line 66
    // Line 67 is here
    if (!$statement) // Line 68
    throw new Exception($statement->error);

    $statement->bind_param(“isssss”, $Facebookid, $firstname, $lastname, $FBpictureURL, $Gender, $UserEmail);
    $returnValue = $statement->execute();

    return $returnValue;
    }

    • Senty, thank you for your message. I cannot spot and error in your code you pasted here. Can you check the line with $sql=””; that there is no line breaks and the entire line of code is on one line? Also, if you copied and pasted these lines of code. Try typing them manually, just to avoid some fonts and encodings issues.

  • Pingback: Connecting to MYSQL with PHP failing (+Swift) - DexPage()

  • Scott

    Hi Sergey. Not familiar with WebServers and PHP. Obviously on a Mac, with Apache and PHP active and MySQL installed and running. I am connecting using localhost and using a login I added to the user table (scott, ). What directory do the 4 PHP files go in and for the NSURL string do I just use “localhost/Register.php” for example?

    • Yes. And it will also depend on your folder structure under htdocs. Usually on localhost if you create a file inside of htdocs folder then you should be able to access it via http://localhost/.php and if you create a subfolder under htdocs then you can access files in it by going to http://localhost//.php

      • Scott

        Great. I installed everything in default directories so looks like I can reach localhost.Conn.php in my browser (prints to screen). That file resides in /Library/WebServer/Documents so I will create all of them in there. Also, I have MySQL running so I assume there is nothing else needed to let the PHP files access MySQL and run queries?

        Thanks for the great tutorial…

        • SergeyKargopolov

          In case of additional software? no. Apache, PHP and MYSQL is all you need. I am in the process of uploading a new video course(40+ videos) for Udemy on User sign up, sign in, password reset, email verification and more with Swift and PHP+MYSQL. I will send out a notification email when new videos become available. If you would like to receive notification, you can subscribe to my blog and you will not miss new videos. Happy coding!

  • Scott

    Hi Again Sergey. I finished the code for both registering and logging in. They both work to your server using your test email and password (sergey@earthlandia.com / 1234). So yeah! My apologies for adding my seh@scott.com (fake) to your user table.

    I have not been able to connect to my “localhost” server to test hence why I tried your server which worked. This is what I have: let myURL = NSURL(string: “http://localhost/userLogin.php”). Is this the right URL? Hope you or someone can help as I am so close to understanding how this works.

    Also, if we put a “Cancel Registration” button on the Registration page, this should send us back to Login page. I tried both of the following (one at a time):

    @IBAction func cancelRegistration(sender: AnyObject) {

    //self.performSegueWithIdentifier(“cancelToLoginView”, sender: self)
    self.dismissViewControllerAnimated(true, completion: nil)
    }

    For the commented Segue line, I created a segue with the correct name. Now both of these do send me back to the login page but with a warning:

    SQLRegistration[77216:7724158] Warning: Attempt to present on whose view is not in the window hierarchy!

    What is the simple way to return to the login page if the user taps “Cancel Registration”

    • Hi Scot! self.dismissViewControllerAnimated(true, completion: nil) should work and dismiss view controller if it was presented modally. Can you mare sure that the cancelRegistration function gets triggered?

      I will try to help you of course. I could also look at your project if you send it to me zipped to make it working… have a look at this video course I created and let me know if you are interested in enrolling. http://goo.gl/gTxpwH

  • Rodrigo Augusto Marques

    Hi,
    I would like to thank you by this video course. It was very usefull to me.

    There are any place where I can download whole package of this project containing .swift files, .php files and, but not mandatory, mysql scripts?
    Kind Regards,
    Rodrigo

  • Garret

    Hey Sergey,

    I’m trying to do exactly what your doing and I’m using the PHP Scripts word for word that you have written except I’m substituting my data base info in but I keep getting this error in my error log whenever I run it that says:

    PHP Parse error: syntax error, unexpected ‘required’ (T_STRING) in /home8/pixacour/public_html/userRegistration.php on line 10

    I don’t know what I’m doing wrong please help!

  • Yanoth EL

    $config = parse_ini_file(‘../../../../SwiftCourse2.ini’); I do not know where the file above location after I download it from github

  • Chris Brown

    This a great app for learning, thank you. I wonder if you can help with my error on the user login swift script:-

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

    I get an error “Extra argument error in call” and it highlights the “&err”

    When I type the line
    var json = NSJSONSerialization.JSONObjectWithData(, options: )

    it doesn’t show the error as a parameter, yet if i leave it out I get a build error, saying ‘Call can throw, but it’s not marked with try and the error isn’t handled!!)

    Hope you can help. By the way i’m using Xcode 7, if that could be the problem!

    Thanks
    Chris

    • Hi Chris! Here is how you need to do it in Xcode 7

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

      if let parseJSON = json {

      }

      } catch
      {
      print(error)
      }

      • Chris Brown

        Thank you!
        Really appreciate your help
        Chris

  • Shamilla Selamat

    Sergey, thanks for the tutorial! It’s awesome!
    However, I was unable to get user registration to work. I followed your tutorial, did not change anything much except the table for users. But I can’t seem to get it working. There is no error, no nothing, I am clueless on what should I do. Please help?
    Thanks!

    • Do you think you can check if your script establishes connection with MySQL correctly? Meaning there is a connection and you can read values from database.

      • Shamilla Selamat

        I think my php script establishes connection with MySQL correctly as when I load this http://localhost/~shamillaselamat/vrooming/registeruser.php on safari it shows {“status”:”Error”,”message”:”Missing required field”}.

        // Sending data to server

        let url = NSURL(string: “http://localhost/~shamillaselamat/vrooming/registeruser.php”)

        let request = NSMutableURLRequest(URL: url!)
        request.HTTPMethod = “POST”

        let level_id: Int = 1

        let postString = “username=(email)&password=(password)&level_id=(level_id)&id_no=(idNo)”

        request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)

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

        data, response, error in

        if error != nil {
        println(“Error = (error)”)
        return
        }

        var err: NSError?

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

        if let parseJSON = json {

        var resultValue = parseJSON[“status”] as? String

        println(“Result: (resultValue)”)

        var isUserRegistered: Bool = false

        if(resultValue == “Success”) { isUserRegistered = true }

        var messageToDisplay: String = parseJSON[“message”] as! String!

        if(!isUserRegistered) {

        messageToDisplay = parseJSON[“message”] as! String!

        }

        dispatch_async(dispatch_get_main_queue(), {

        var alert = UIAlertController(title: resultValue, message: messageToDisplay, preferredStyle: UIAlertControllerStyle.Alert)

        let action = UIAlertAction(title: “OK”, style: UIAlertActionStyle.Default) { action in

        self.dismissViewControllerAnimated(true, completion: nil)

        }

        alert.addAction(action)
        self.presentViewController(alert, animated: true, completion: nil)
        })
        }
        }

        What do you think? I’m sorry, this is my first app using swift.

        • Mathias Verhoeven

          I am having the same problem. Does someone know a solution?

          • Please check my answer above.

          • Mathias Verhoeven

            Hello, I tried your solution from above but I still recieve the following error in swift. Any ideas?

            Error Domain=NSCocoaErrorDomain Code=3840 “JSON text did not start with array or object and option to allow fragments not set.” UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}

            Error Domain=NSCocoaErrorDomain Code=3840 “JSON text did not start with array or object and option to allow fragments not set.” UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}

          • Anthony Rodriguez

            I am too receiving the same error I have tried the debug with the script provided in my php file…It shows okay until put here:

            $email = htmlentities($_POST[“email”]);

            $password = htmlentities($_POST[“password”]);

            //DEBUGGING CODE
            //$returnValue[“status”] = “AFTER LINE 1”;
            //echo json_encode($returnValue);
            //return;

            //This works if I comment out the POST…
            //$email = “d”;
            //$password = “1”;

            Thank you john.

          • Mathias, when you debug line by line as I suggested above, which line does it stop at?

          • Greg Hanley

            Mathias – I am having the exact same issue here!

            Sergey – I debugged and the line that is causing the problem is the following:

            do {

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

            It goes to “let json = try…” line, but then jumps to the catch, and prints the error!

            Really want to get this working – any suggestions? Great tutorial!

        • Can you debug or print out the value of postString to see if parameter values are all in place?

          let postString = “username=(email)&password=(password)&level_id=(level_id)&id_no=(idNo)”

          Also please check in your php script that http parameters you are sending it and parameter names you use to read them are the same and there are no typos. There must be some kind of response. If there is still not response then try to catch it by adding “echo” after each significant piece of php code. For example in your php code you will do:

          $returnValue[“status”] = “AFTER LINE 1”;
          echo json_encode($returnValue);
          return;

          if that worked, then cut it out and paste a few line blow and see if that sends valid response to your Swift app. This was you will be able to narrow down a piece of code in you php script that causes the problem.

          • Shamilla Selamat

            Thanks Sergey! It works! Finally! Your tutorial is awesome, I don’t know why it doesn’t work before as I actually re-do the whole thing and it works! Thanks again!

          • Awesome! 🙂 I am happy it worked! Good luck with your project!

  • Hrach

    Really great, clean tutorial with very accurate scripting! Thanks!

  • Mamadou Asse AMAR

    Hey Sergey,

    First, I want to thank you for this tutorial ! it is very useful !!

    But I have a problem with my RegisterPageViewControler in Xcode. I have an error, so I can not run the simulator.

    Here is my codes:

    var jsonError: NSError?
    var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers, error: &err) as? NSDictionary

    The error message is “Use of unresolved identifier ‘err’.

    Please help me!

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

      if let parseJSON = json
      {
      }

      }catch
      {
      print(error)
      }

  • dn

    Hello Sergey . Very good tutorial and help .

    I ‘ve done it all , and when I run and try to enter data have been successful . But when I look at my database there are additional words ” Optional ( & quot; user@host.com&quot ; ) ” . Please help me. Thank you

    • dn, In your swift code, before sending out values, unwrap them by adding “!” to each. For example, before using value of emailAddress, use emailAddress! please note an exclamation mark at the end. This will not solve your problem with Optional.

      • dn

        Wow. It’s work! Thank you very much for helping me. If you are willing, can you teach me how to retrieve data from the database to the application? Can also edit, delete, and update.

        Thank you very much for the awesome tutorial! 🙂

    • Dn, before making use of variables(optionals) in your Swift file, add “!” exclamation mark at the end. This will make variables sent to your PHP scripts without the “Optional()” added to them

  • Hrach

    Yesterday I have purchased one of your tutorials from udemy.com (user sign in, sign up and more…). Very good tutorial. Just I would like to know a little more about
    “security”. For example: how to add a token variable in HTTP header or is it necessary? Also I will be glad to get some information about SSL requirements and setup on server side, as I’m going to make my app available on App Store (currently I temporary allowed arbitrary loads in order to connect to my server via http://).
    Thanks a lot to author.
    P.S. if the tutorials will be available on russian also, it will be perfect.

    • Hrach, thank you for your message. Regarding the SSL certificate. The best way is to contact your website/server hosting provider and purchase SSL certificate from them. Usually, web hosting is sold with SSL certificates enabled already, so you do not need to install and configure them yourself…. As to how to add custom header value(like a secure token) to a header when sending HTTP POST request then you can have a look at this discussion: http://stackoverflow.com/questions/8115683/php-curl-custom-headers

      • Hrach

        Hi Sergey, thank You very much!

        For a token in header i have done this way (I don’t know is it good idea but I did..)))

        Server side:
        foreach ($_SERVER as $nam=>$val) {
        if ($nam == ‘HTTP_TOKEN’) {
        // my code
        }}

        App side:

        myRequest.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)

        myRequest.addValue(“application/json”, forHTTPHeaderField: “Token”)

        myRequest.setValue(“some string”, forHTTPHeaderField: “Token”)

        • Hrach, in you app script you are setting two header values both with same name. One will be enough. For example:

          myRequest.setValue(“some string”, forHTTPHeaderField: “Token”)

          also if you are setting a header value for key name: “Token” then in you PHP script you should read this value by the same name “Token” other wise it will not be found.

          • Hrach

            Dear Sergey, it is strange, but the Token automatically is converting to HTTP_TOKEN. When I’m dumping $_SERVER instead the Token I see HTTP_TOKEN.
            For me just the .addValue don’t work, so I have to additionally set its value. Thanks for your replies.

          • Do you get correct value when you print $_SERVER[‘HTTP_TOKEN’] ?

          • Hrach

            Yes ))

  • Yi Zhu

    Hi kargopolov,

    Thanks for this tutorial. May I ask what do you mean by “Now, let’s implement Conn.php script”? How to implement php file? Do I supposed to upload in to mysql database under the “user” table that I created? Thank you!

    • php file is just like any text file but with .php extension. When this .php file is placed inside the web folder and is accessed via web browser it will be processed in a special way when php scripts you typed inside of this file will be executed. All files with extension .php need to be placed under your web folder. You will need to look for additional tutorials on building web pages with PHP…

      • Yi Zhu

        Thank you! I did set up the PHP page, and put those .php files under the web folder. However, they are all local, though can be viewed by the browser. The MySQL server I am using is not local, however, it is online. Will this be a problem if I use local .php file to connect with the online MySQL database? Also you created a http://www.earthlandia.com/user-register/userRegister.php. Could you tell me how and where I can created something similar to this file, and how does this file related to MySQL and PHP? Thanks much!

        • Yes, you can connect to a remote MySQL database server from your PHP script running on local host. In your connection file use IP address of your server + “:3306” instead of localhost. For example 212.34.145.67:3306 where the IP address should be the IP address of your remote server. Also on remote reserver port number 3306 should be open. Other wise connection will not be established…. Regarding your question on How and where you can create a remote PHP script: You need to have a hosting plan with one of server providers like GoDaddy for example. Once you have your account, you can learn from them or their online help how to upload your own PHP scripts to your remote web folder. Also you can ask them to open port 3306 for your remote database connections if this port happens to be closed for your account.

          • Yi Zhu

            Thanks for this detailed reply! Are you familiar with Plesk? I have a Plesk account which run by my university. With it, I can create a MySQL database and create the table in it. The problem for me now is I don’t know how this MySQL database can connect with those .php files. Where should I put those .php files in order to quarry the MySQL database? I tried to upload those .php files onto a Plesk file folder, however I don’t think they are connected with MySQL. And once I view the uploaded .php file in the browser, it didn’t show anything, and some of them even showed “Server Error”. Is it supposed to be like this, is it normal? Thank you!

          • If you are getting Server Error then it mean you have an error in your php script. Try to debug your code line by line from top to bottom and see where your script breaks…

            As to connection to your mysql database. PHP files need to go into your web folder. There is no other place to place them. If you place php files outside the web folder then you will not be able to access then via browser window. Ask you tech support for MySQL database connection details. Send them a message and ask them to guide you where to find these details. What should be the hostname? what should be the user and what should be the password? also let them know that you would like to connect from your local computer and what would the the IP/hostname and this case. And you will see that for remote connection your IP/Host name will have (most probably) port number 3306 attached to it.

  • will_updike

    Hi,
    Really nice tutorial! But I’m struggling to get it working with swift 2.0.
    Can you check what the error is in my code?
    pastebin.com/8g3QLz1M

    I have all the PHP files uploaded. But I can’t get It’s working. It constantly is saying result: error and if I leave the text field blank it says nothing.
    Please help.

    • sorry for this late reply… did you get it working?

  • ChewMPMC

    I had 12 errors in my script

    import UIKit

    class RegisterpageViewController: UIViewController
    {

    @IBOutlet weak var userNameTextField: UITextField!

    @IBOutlet weak var userICTextField: UITextField!

    @IBOutlet weak var userPasswordTextField: UITextField!

    @IBOutlet weak var repeatPasswordTextField: UITextField!

    override func
    viewDidLoad() {

    super.viewDidLoad()

    // Do any additional setup after loading the view.

    }

    override func
    didReceiveMemoryWarning() {

    super.didReceiveMemoryWarning()

    // Dispose of any resources that can be recreated.

    }

    @IBAction func
    registerButtonTapped(sender: AnyObject) {

    let userIC = userICTextField.text;

    let userPassword = userPasswordTextField.text;

    let userRepeatPassword = repeatPasswordTextField.text;

    let userName = userNameTextField.text;

    // Check for empty fields

    if(userName!.isEmpty
    || userIC!.isEmpty || userPassword!.isEmpty || userRepeatPassword!.isEmpty)

    {

    //Display alert messege

    displayMyAlertMessage(“All
    fields are required”);

    return;

    }

    // Check if passwords match

    if(userPassword != userRepeatPassword)

    {

    // Display an alert messege

    displayMyAlertMessage(“Passwords
    do not match”);

    return;

    }

    // Send user data to Server side

    let
    myURL = NSURL(string:”http://taa2016.freetzi.com/Taa2016/userRegister.php”)

    let request = NSMutableURLRequest(URL:
    myURL!)

    request.HTTPMethod = “POST”;

    let postString = “email
    =(userIC)&password=(userPassword)&name=(userName)”;

    request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);

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

    data,
    response, error in

    if error != nil
    {

    print(“error=(error)”)

    return

    }

    do {

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

    if let
    parseJSON = json

    {

    }

    }catch

    {

    print(error)

    }

    if let
    parseJSON = json {

    var resultValue = parseJSON(“status”) as?
    String

    print(“result: (resultValue)”)

    var isUserRegistered:Bool
    = false;

    if(resultValue==”Success”)
    {isUserRegistered = true;}

    var messageToDisplay:String
    = parseJSON[“message”] as string!;

    if(!isUserRegistered)

    {

    messageToDisplay = parseJSON[“message”]
    as String;

    }

    dispatch_async(dispatch_get_main_queue(),
    {

    // Display alert message with confirmation.

    var myAlert = UIAlertController(title:”Alert”,
    message:messageToDisplay, preferredStyle: UIAlertControllerStyle.Alert);

    let okAction = UIAlertAction(title:”Ok”,
    style:UIAlertActionStyle.Default){ action in
    self.dismissViewControllerAnimated(true, completion: nil);

    }

    myAlert.addAction(okAction);

    self.presentViewController(myAlert,
    animated:true, completion:nil);

    });

    }

    /*

    // MARK: – Navigation

    // In a storyboard-based application, you will often want to do a little
    preparation before navigation

    override func prepareForSegue(segue: UIStoryboardSegue, sender:
    AnyObject?) {

    // Get the new view controller using segue.destinationViewController.

    // Pass the selected object to the new view controller.

    }

    */

    }

    task.resume();

    Can you help me check?

    • What is the very first error do you get with this script?

  • p_r_o

    Hey there! Great tutorial and I will thank you a lot! I have one
    problem that I am facing and I want to ask you about it even though it is a while ago you have made this tutorial.

    I can connect to my database and everytime I try to register a user it gives me the message “Missing required field” and that is the message when all the fields are not filled but rather empty even though I do fill them out. I then went to userRegister.php and removed the part of checking whether email or password is empty or not.

    After that I could successfully add a row to my database but what happened first time is that it added an empty string for the email row and md5 password for password row. No matter what username or password I do use I will now receive the message “User already exists”

    Later on I deleted the row from my database and tried again (and I again removed the checking of empty email or password as this is still bugged) and now it just adds a 0 for email row and 0 for password row. I really have no idea why it is not using the data I type.

    When I print the username and password textfields they return me the value that I actually write and in addition to this; it works when I use your server.

    Regarding the php I have tried copy/pasting and I have tried writing them with my own hands and even further checked for any mistakes. I have no clue why I can’t get it to work I hope you can help me out

    (I edited the post as the lines were messed and the message was not really readable..)

    • p_r_o

      There is an update..

      If I echo $email it displays nothing (its empty) but if I set it to something specific like:

      $email = “emailaddress”;

      and then echo it I will see the text: “emailaddress”;

      What could possibly go wrong considering that my swift code works with your php files (which should mean that swift code is free from error)?

      • p_r_o

        It worked when I tried it locally.. Those of you who have this problem try a local server (I used MAMP in this case). I put the files in htdocs folder..

        • Thank you!

          • p_r_o

            It is me who has to thank you 🙂

  • Mahesh

    I am getting this error in xcode: Error Domain=NSCocoaErrorDomain
    Code=3840 “JSON text did not start with array or object and option to
    allow fragments not set.”

    Please check my code

    let myUrl = NSURL(string: “http://www.01coders.com/ios/userRegister.php”);
    let request = NSMutableURLRequest(URL : myUrl!);
    request.HTTPMethod = “POST”;

    let postString = “username=(username)&password=(password)”;

    request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);

    let task = NSURLSession.sharedSession().dataTaskWithRequest(request){
    data, response, error -> Void in

    if (error != nil){
    print(“error=(error)”)
    return
    }

    do{

    let json = try NSJSONSerialization.JSONObjectWithData(data!, options:
    NSJSONReadingOptions.AllowFragments) as! NSDictionary

    print(“json: (json)”);

    let resultValue = json[“status”] as! String;
    print(“Result: (resultValue)”)

    var isUserRegistered:Bool = false;

    if(resultValue==”Success”){
    isUserRegistered = true;
    }

    var messageTodisplay:String = json[“message”] as! String;

    if(!isUserRegistered){
    messageTodisplay = json[“message”] as! String;
    }

    dispatch_async(dispatch_get_main_queue(), {

    let myAlert = UIAlertController(title: “Alert”, message:
    messageTodisplay, preferredStyle: UIAlertControllerStyle.Alert);

    let okaction = UIAlertAction(title: “Ok”, style: UIAlertActionStyle.Default, handler: nil);

    myAlert.addAction(okaction);

    self.presentViewController(myAlert, animated:true, completion:nil);
    })

    }catch let error as NSError{
    print(error)
    }
    }
    task.resume();

    • This means that your php script returns value which cannot be parsed to JSON. Most probably there is an issue in php script which results in an error. Can you double check your php script?

    • Mahesh

      Thanks.

      I have doubled check my PHP script, It is giving an error because “mysqli_connect” function not working in my script then I have replaced with “mysql_connect”, now it is not giving any error but nothing is updating in database.

      Do you have any PHP script for that? If you have can you please send me?

  • Alexander

    Hi, For:

    $secure_password = md5($password);

    $dao = new MySQLDao();
    $dao->openConnection();
    $userDetails = $dao->getUserDetailsWithPassword($email,$secure_password);

    How would i do this for Bcrypt. I have used ruby on rails with devise to create the passwords stored in the DB…

  • Aravind

    Hi
    while i am running the app in the simulator and registering the details when the register button is tapped it is getting crashed and showing me the error EXC_BAD_INSTRUCTION(code=EXC_1386_INVOP,subcode=0x0)
    could you please help me
    i am new to swift

  • Aravind

    Hi
    while i am running the app in the simulator and registering the details when the register button is tapped it is getting crashed and showing me the error EXC_BAD_INSTRUCTION(code=EXC_1386_INVOP,subcode=0x0)
    could you please help me
    i am new to swift

  • Martin

    Hi Sergey!

    Now since Parse is being killed I need to move my app data elsewhere.

    I’ve followed your tutorial and I can register successfully. However, I can’t login! Response from server side is “error”, “User is not found”.

    I have copied your php scripts without exception. I don’t know exactly where I fail; I find it hard to error-code in php when input comes from my app.

    Is your php still up-to-date? I mean, it’s been a while since you posted this and maybe things have changed? I have to say I find it hard to follow when you use $userPassword in the MySQLDao.php and $secure_password when you call the function from userLogin.php. Can you explain this further?

    Sincerely,

    Martin (big fan!)

    • Martin

      I’ve looked further into this. Look at these 3 statements:

      1. the correct username and password are sent to the php script.
      2. the getUserDetails function in the dao-script works fine; I get the response that the user exists when trying to register.
      3. the getUserDetails and the getUserDetailsWithPassword functions are exactly the same, apart from the fact that the latter is trying to query the given password.

      Something’s up with the password. They don’t match! But I have no idea what I’m doing wrong!!

      • Martin

        One more thing I’ve noticed is that the secure_password is crypted to one string when signing up and another when I try to sign in. Now, I read somewhere that this shouldn’t matter but if it does, one can clearly understand why there is no match from the getUserDetailsWithPassword function…

        Just thought I’d let you know as much as possible. Any suggestions much appreciated.

        • Martin

          Sorry for bothering you like this, but I found a solution, however not at satisfying one. It seems like the secure_password is messing things up, since when I go with plain password in and out it works. It’s good to know the code works anyway.

          You think it has something to do with collations? My database is all utf8 and I first forgot to set it.

          I got these quote inserts in my password too, which I didn’t notice until I skipped the md5. That probably had to do with my userPassword from swift came in as an optional…

          This post shouldn’t have been this long. When you have time I would love to hear what you think about it and what I should do.

          Martin

          • Hi Martin! Sorry for delayed response!. Can you confirm that user name and password you send to php script both when registering (a user and when login in) do not contain Optional()?

          • Martin

            Hi Sergey!

            Thank you for replying. Don’t worry about any delays, I’ve kept myself busy with some other tutorials of yours. You have been of massive help so far. Thank you!

            As with this problem I will continue my error search according to your answers. I know my values from swift are not optional, but it was a good suggestion (I’ve missed it before).

            So, maybe it’s the collations. I had everything set to utf8mb4 (since I read on Stackoverflow that it should be used to accept some special Swedish characters). I know how to change collation in MySQL, but I’m still a beginner. Is there anything in particular you’d suggest? Do I need to set all tables and all fields to utf-8, or is it enough with just the password field? Should I use unicode, genereal or something else?

            Again, thank you Sergey!

          • Hi Martin! Sorry for delayed response!. Can you confirm that user name and password you send to php script both when registering (a user and when login in) do not contain Optional()?

          • Also Martin, which language do you type your password in? Does it have special characters? To be safe you should use UTF-8 for your database not sure if I show how to do it in my video. Do you have access to my video course on Udemy?

    • Martin, when you register user, can you double check if userEmail and password which are sent from Swift app to php script do not contain Optional() around the value? You can print value of userName and password into Xcode console before sending it and see if values are correct. Just want to make sure that these values get recorded into database properly.

  • Taehoon K

    The best tutorial ever.
    I literally searched all for two days and this one is the only one that actually helps.
    Thank you for your posting!

  • Greg Hanley

    Hi Sergey,

    Great Tutorial – running into problems though!

    I have altered the PHP to suit my app (FacebookID, e-mail, name – the 3 variables which I wish to store in MySQL Database after a new user authenticates the app, using the FacebookSDKLogin).

    Basicaly, I want to write the 3 above variables to the “users” table after succesfully logging in through Facebook/Authenticating the App I am developing.

    However, at the following line I am getting troubles:

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

    When debugging, I get the following error after this line:

    Error Domain=NSCocoaErrorDomain Code=3840 “JSON text did not start with array or object and option to allow fragments not set.” UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}

    As a result, I replaced “.MutableContainers” with “.AllowFragments”. Now, I am getting the following error:

    Error Domain=NSCocoaErrorDomain Code=3840 “Invalid value around character 1.”

    I am very frustrated as I need to get this up and running soon!

    Please find here all of the code which pertains to this tutorial, which is run after the user verifies the app after Facebook login:

    // Send user data to server side

    let myUrl = NSURL(string: “http://<<>>.ie/greghanley3/ReelTime/userRegister.php”);

    let request = NSMutableURLRequest(URL: myUrl!);

    request.HTTPMethod = “POST”;

    let postString = “id=(userID)&email=(userEmail)&name=(userName)”;

    let trimmedPostString = postString.stringByReplacingOccurrencesOfString(” “, withString: “”)

    request.HTTPBody = trimmedPostString.dataUsingEncoding(NSUTF8StringEncoding);

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

    data, response, error in

    print(“Begin MySQL Process!”)

    print(data)

    print(postString)

    print(trimmedPostString)

    if error != nil {

    print(“error=(error)”)

    return

    }

    do {

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

    if let parseJSON = json {

    var resultValue = parseJSON[“status”] as? String

    print(“result: (resultValue)”)

    var isUserRegistered:Bool = false;

    if(resultValue==”Success”) { isUserRegistered = true; }

    var messageToDisplay:String = parseJSON[“message”] as! String!;

    if(!isUserRegistered)

    {

    messageToDisplay = parseJSON[“message”] as! String!;

    }

    }

    }catch { print(error) }

    }

    task.resume()

    • Greg, the error you are getting in Swift app is because your php script does not return correct JSON and most probably because there is error takes place in php script….

      1. In your Swift app please print values of “postString”.. is if userId and userEmail and userName are now wrapped into Optional(). if they are then add an exclamation mark after each to unwrap it. Like so:

      let postString = “id=(userID!)&email=(userEmail!)&name=(userName!)”;

      2. Try running your php script by accessing it’s URL via the browser window. For example open this url in browser window and pass request parameters to it manually like so:
      http://<<>&gt;.ie/greghanley3/ReelTime/userRegister.php?id=57&email=sergey@mywebsite.com&name=Sergey

      What will you get as response?

      also, if you test your php script via the browser address bar like I suggested above, please change $_POST in your php script to $_REQUEST, so that you can read request parameters send as POST and GET as well.

      • Greg Hanley

        Hi Sergey,

        Thank you very much for your comprehensive reply! I will give the above a shot as soon as I get the chance and will let you know the outcome! I have changed the .PHP scripts to suit my needs (id, email, name instead of email, password) so there must be an issue in there somewhere!

        So is .MutableContainers the correct “options” parameter? And not .AllowFragments?

        Thanks again for the extremely useful tutorial! Sorry about the questions, it’s just I can’t find anything else online that is as useful as this, and that suits my requirements as much!

        I look forward to continuing your series of tutorials here, keep up the great work!! ?

        Kind Regards,
        Greg.

      • Greg Hanley

        Hi Sergey,

        I have made a new PHP Script (testInsert.php) which I know to work for inserting as you mentioned, using $_REQUEST, and I was able to insert a record from the URL (e.g “http://<<>>.ie/greghanley3/ReelTime/userRegister.php?id=57&email=sergey@mywebsite.com&name=Sergey” – entered the MySQL database correctly). As a result, I decided to change back to “$_POST” and to use this new PHP page as the “myURL = ” variable.

        I was still getting the same error, so I tried to add the exclamation marks after the three variables in the postString as you mentioned above, but got the following error form XCode:

        “Cannot force unwrap value on non-optional type NSString.”

        This is the code in which I obtain the users FB information once they verify the app after login:

        let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: “me”, parameters: [“fields”:”id, name, email”])

        graphRequest.startWithCompletionHandler({ (connection, result, error) -> Void in

        if ((error) != nil)

        {
        // Process error
        print(“Error: (error)”)
        }

        else

        {

        print(“fetched user: (result)”)

        let userID : NSString = result.valueForKey(“id”) as! NSString

        print (“User Facebook ID is: (userID)”)

        let userEmail : NSString = result.valueForKey(“email”) as! NSString

        print(“User Email is: (userEmail)”)

        let userName : NSString = result.valueForKey(“name”) as! NSString

        print(“User Name is: (userName)”)

        However, with this new PHP script, even though I am still getting the same error as before (“Error Domain=NSCocoaErrorDomain Code=3840 “JSON text did not start with array or object and option to allow fragments not set.”), the data is actually inserting into the MySQL database successfully!? My FacebookID, email address and name are all inserting correctly into MySQL, as they should!

        When I print the “data” variable I get the following:

        “Optional()”.

        Any ideas why the data is inserting correctly, even though I am still getting this error!?

        Thanks once again Sergey, really appreciate all of your hard work :).

  • Chris Garand

    Firstly, I’d like to thank you Sergey for these great tutorials, they’ve been immensely helpful in my learning JSON, PHP, MySQL, and Swift. I have a serious point to make regarding md5, it’s not al all secure (hashing is easily decipherable) which every reader should know.
    Are there other issues? Of course, and I’m sure you know of them, but seeing as this is more of an all inclusive introduction, the readers can do their own research (or hopefully look at your other tutorials/courses where I’m sure you cover it).

    • Hi Chris, thank you for your message. Yes, md5() along is not enough. Today I do it this way:

      //Generate secure password
      $userPassword = htmlentities($_POST[“userPassword”]);
      $salt = openssl_random_pseudo_bytes(16);
      $secured_password = sha1($userPassword . $salt);

      • Chris Garand

        I was doing some reading Sergey, and might I suggest (in PHP 5.5+) using password_hash(), it automatically will use the most up to date algorithm (with PASSWORD_DEFAULT, for your php version) and automatically salts the hash, allowing you to store a single string for the salted and hashed password. Password verification is also a snap using the password_verify() function.

  • Luis Perez

    hi, im getting a compiler error at the line
    var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers, error: err?) as? NSDictionary

    it says that i put an extra argument (error) in the call, can you help me ?

    • Try this way:

      do {

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

      // Your code here

      } catch { print(error)}

      • George Bush

        is it somehting like this?

        do {

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

        var err: NSError

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

        if let parseJSON = json {

        var resultValue = parseJSON[“status”] as? String

        print(“result:(resultValue)”)

        var isUserRegistered:Bool = false

        if resultValue == “Success” {

        isUserRegistered = true

        }

        var messageToDisplay:String = parseJSON[“message”] as String!

        if !isUserRegistered {

        messageToDisplay = parseJSON[“message”] as String!

        }

        dispatch_async(dispatch_get_main_queue(), {

        var myAlert = UIAlertController(title: “Alert”, message: messageToDisplay, preferredStyle: UIAlertControllerStyle.Alert)

        let okAction = UIAlertAction(title: “Ok”, style: UIAlertActionStyle.Default) { action in

        self.dismissViewControllerAnimated(true, completion: nil)

        }

        myAlert.addAction(okAction)

        self.presentViewController(myAlert, animated: true, completion: nil)

        })

        }

        }

        task.resume()

        } catch {

        print(error)

        }

        • No need for these lines anymore:
          let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary

          var err: NSError

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

          remove them!

          Use this instead:

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

          and a complete example is:

          do {

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

          // Your code here

          } catch { print(error)}

  • praveen

    i am create a registretion page and database .now how i will connect the both

  • Solkin

    Hi Sergey
    Thanks for this tutorial. It’s very good, I need some help on the registerViewController.swift, when debugging I get “Extra argument ‘error’ in call” …&err in this line:

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

    I will appreciate if you can tell me how to fix this. Thanks!

    here’s the code:

    import UIKit

    class RegisterPageViewController: UIViewController {
    @IBOutlet weak var userEmailTextField: UITextField!
    @IBOutlet weak var userPasswordTextField: UITextField!
    @IBOutlet weak var confirmPasswordTextField: UITextField!

    override func viewDidLoad() {

    super.viewDidLoad()

    // Do any additional setup after loading the view.

    }

    override func didReceiveMemoryWarning(){

    super.didReceiveMemoryWarning()

    // Dispose of any resources that can be recreated.

    }

    @IBAction func registerButtonTapped(sender: AnyObject){
    let userEmail = userEmailTextField.text;
    let userPassword = userPasswordTextField.text;
    let userConfirmPassword = confirmPasswordTextField.text;

    // check for empty fields
    if (userEmail!.isEmpty || userPassword!.isEmpty || userConfirmPassword!.isEmpty)

    {

    // display alert message
    displayMyAlertMessage(“All fields are required”);
    return;
    }

    // check if password match
    if (userPassword != userConfirmPassword){
    // display alert message
    displayMyAlertMessage (“pasword not match”);
    return;
    }

    // Send user data to server-side
    let myUrl = NSURL(string: “http://tripper.backend/bl/userRegister.php”);

    let request = NSMutableURLRequest(URL: myUrl!);
    request.HTTPMethod = “POST”;
    let postString = “email=(userEmail)&password=(userPassword)”;
    request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);

    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
    data, response, error in

    if error != nil {
    print(“error=(error)”)
    return
    }

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

    if let parseJSON = json {
    var resultValue = parseJSON[“status”] as? String
    println(“result: (resultValue)”)

    var isUserRegistered:Bool = false;
    if (resultValue==”Success”){isUserRegistered = true;}
    var messageToDisplay:String = parseJSON[“message”] as String!;
    if(!isUserRegistered)
    {

    messageToDisplay = parseJSON[“message”] as String!;
    }

    dispatch_async(dispatch_get_main_queue(), {

    //Display alert message with confirmation
    var myAlert = UIAlertController(title: “Alert”, message:messageToDisplay, preferredStyle: UIAlertControllerStyle.Alert);

    let okAction = UIAlertAction(title: “Ok”, style: UIAlertActionStyle.Default){ action in
    self.dismissViewControllerAnimated(true, completion: nil);
    }

    myAlert.addAction(okAction);
    self.presentViewController(myAlert, animated: true, completion: nil);
    });

    }

    }

    task.resume()

    }

    func displayMyAlertMessage(userMessage:String) {

    let myAlert = UIAlertController (title: “Alert”, message: userMessage, preferredStyle: UIAlertControllerStyle.Alert);

    let okAction = UIAlertAction(title: “OK”, style: UIAlertActionStyle.Default, handler:nil);

    myAlert.addAction(okAction);

    self.presentViewController(myAlert, animated: true, completion: nil)

    }

    }

    • try converting data into json this way:

      do {

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

      // Your code here

      } catch { print(error)}

  • Bryan Posso

    These are the errors I am getting. After reading a few posts about altering the language to the new Swift 2.0….still having a lot of issues.

    Thanks

  • rahim jessani

    I tried with the url you provided with that url it works fine but when i hosted my page and use that it give me this error

    Error Domain=NSCocoaErrorDomain Code=3840 “JSON text did not start with array or object and option to allow fragments not set.” UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}

    • This means that your php script did not return a valid JSON and most probably because of an error taking place in your php script. Try running php script via the browser address bar and pass request parameters via the query string. For example: http://www.mywebsite.com/myscripts/myScript.php?userNameParam=Sergey&userPasswordParam=123 and see what would you browser print..

      • Константин Шишкин

        have the same problem, get this. If I try go to page from brouser as you write before but with my email, login, website and etc, i see in brouser {“status”:”error”,”message”:”Missing required field”}, what it mean?

        • Richard

          I have just done as you suggest Serge, and get the same {“status”:”error”,”message”:”Missing required field”} error – so glad I’m not the only one! 🙂

  • NickSmith1991

    Hi Sergey
    Would just like to say this is the best user-login-register course I’ve found, thanks a million!
    I’ve liked it so much I’m going to register for your udemy course and continue the learning.

    One thing, I seem to be getting the same error that many are getting, that “extra “error” argument in call” in var json. Tried to implement your suggested solution but doesn’t look like its working out?
    I might be adding it in incorrectly.

    Any suggestions?

  • NickSmith1991

    Hi Sergey
    Would just like to say this is the best user-login-register course I’ve found, thanks a million!
    I’ve liked it so much I’m going to register for your udemy course and continue the learning.

    One thing, I seem to be getting the same error that many are getting, that “extra “error” argument in call” in var json. Tried to implement your suggested solution but doesn’t look like its working out?
    I might be adding it in incorrectly.

    Any suggestions?

    • Sorry, I have just came across this comment. Have you resolved your issue?

  • iAhmadSA ツ

    i fixed ?

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

    data, response, error in

    if error != nil {

    print(“error=(error)”)

    return

    }

    do {

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

    if let parseJSON = json {

    var resultValue = parseJSON[“status”] as! String!

    print(“result: (resultValue)”)

    var isUserRegistered: Bool = false

    if (resultValue == “Success”) {

    isUserRegistered = true

    }

    var messageToDisplay: String = parseJSON[“message”] as! String!

    if (!isUserRegistered)

    {

    messageToDisplay = parseJSON[“message”] as! String!

    }

    dispatch_async(dispatch_get_main_queue(), {

    var myAlert = UIAlertController(title: “Alert”, message: messageToDisplay, preferredStyle: UIAlertControllerStyle.Alert)

    let okAction = UIAlertAction(title: “Ok”, style: UIAlertActionStyle.Default) { action in

    self.dismissViewControllerAnimated(true, completion: nil)

    }

    myAlert.addAction(okAction)

    self.presentViewController(myAlert, animated: true, completion: nil)

    }

    )}

    } catch { print(error)}

    }

    task.resume()

  • Rhys

    Hi all, hopefully someone is able to help me with this seemingly simple problem.

    I ran into the issue with the extra argument error due to running swift 2 but I was able to fix it using the code provided by iAhmadSA ツ in these comments.

    Everything appears to be working great now except when I receive an alert either “Successfully Registered” or “User already exists” when I hit the “Ok” button in the alert it dismisses the current view controller and takes me back to the previous view.

    Is there any way to make it continue to the protected page when the user registers successfully and make it stay on the current view if the user already exists?

    I’m guessing its because the alert view is set to dismiss the view controller when the user clicks “Ok” but I have no idea how to check which alert is received and proceed accordingly. Hopefully this makes sense. Any help would be greatly appreciated.

    For reference I have pasted the code below…

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

    data, response, error in

    if error != nil {

    print(“error=(error)”)

    return

    }

    do {

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

    if let parseJSON = json {

    var resultValue = parseJSON[“status”] as! String!

    print(“result: (resultValue)”)

    var isUserRegistered: Bool = false

    if (resultValue == “Success”) {

    isUserRegistered = true

    }

    var messageToDisplay: String = parseJSON[“message”] as! String!

    if (!isUserRegistered)

    {

    messageToDisplay = parseJSON[“message”] as! String!

    }

    dispatch_async(dispatch_get_main_queue(), {

    var myAlert = UIAlertController(title: “Alert”,
    message: messageToDisplay, preferredStyle: UIAlertControllerStyle.Alert)

    let okAction = UIAlertAction(title: “Ok”, style: UIAlertActionStyle.Default) { action in

    self.dismissViewControllerAnimated(true, completion: nil)

    }

    myAlert.addAction(okAction)

    self.presentViewController(myAlert, animated: true, completion: nil)

    }

    )}

    } catch { print(error)}

    }

    task.resume()

    • In the code that you have pasted here, only alert message is dismissed. ViewController itself should not be dismissed… Try this approach to navigate user to a protected page after alert message is dismissed:

      // You will need to import AppDelegate at the top of script
      // Navigate to Protected page example

      let mainStoryBoard:UIStoryboard = UIStoryboard(name:”Main”, bundle:nil)

      let signInPage:ViewController = mainStoryBoard.instantiateViewControllerWithIdentifier(“ViewController”) as! ViewController

      let signInPageNav = UINavigationController(rootViewController:signInPage)

      let appDelegate:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate

      appDelegate.window?.rootViewController = signInPageNav

      • Rhys

        Hi Sergey, thanks for your reply. Fortunately I was able to resolve this issue by asking the same question over at stack overflow. Basically what I was able to do was check for the json response code and navigate to the protected page if it was successful. I’m sorry I haven’t updated this thread yet as I have extremely busy this week. If you would like to see the full troubleshooting process I went through it can be found here.
        http://stackoverflow.com/questions/36837990/swift-2-php-mysql-sign-up-issue.

        Thanks again Sergey for your great tutorials and your assistance! 🙂

        • You are very much welcome :)!. It’s ok! 🙂

  • mhh

    hello, thank you very much for that great tutorial it’s really helpful
    i’m facing problem with this code, when i run code and try to login the network mentor is zero and the out put is (lldb)

    • Can you debug your code and see if request parameters are not empty and that debugger pointer does actually reach the line when request is sent?

  • ridwan

    I can not login, if there is something wrong. Help me

    • Do you get an error message or any response back?

      • ridwan

        when I click the login button, display an error “result:error”
        please help me.

        • If you print out error message like in the example below. What will it print? :
          print(“error message: (error!.localizedDescription)”)

          • ridwan

            thanks a lot sergey, I learned from you.

          • ridwan

            sergey I want to ask you, what can directly access the database using microsoft sql server.

  • Сергей, добрый день!
    Если в графе вбивать текст кириллицей, то в базу приходит несимпатичный набор символов. Проблема с кодировкой в базе ? или нужно в коде что-то менять/добавлять ?

    Отдельное спасибо Вам за лекции!

    • Oleg, you will need to set mysql database collation to utf8 unicode ci… You can do it using phpMyAdmin. Open your database details and update it’s collation. You can also update collation of specific column by opening Table structure and editing column details-> collation. Please let me know if this helped…. Also, please make sure that you are sending data from your app already UTF-8 encoded. Can you check that?

      • Как-будто все верно. Код ваш, в нем ничего не менял.

  • Huzefa Vakhariya

    Hi Kargopolov, I am getting one error in RegisterationPageViewController.swift. It is saying extra argument in NSJSONSerialization() function when i write third argument of error: &err. I am showing you as image also my error marked red by Xcode and this is my full RegisterationPageViewController.swift code:

    //

    // RegisterPageViewController.swift

    // UserLoginAndRegisteration

    //

    // Created by Admin on 5/24/16.

    // Copyright © 2016 Admin. All rights reserved.

    //

    import UIKit

    class RegisterPageViewController: UIViewController {

    @IBOutlet weak var userEmailtextfield: UITextField!

    @IBOutlet weak var userPasswordTextField: UITextField!

    @IBOutlet weak var userRepeatPasswordTextField: UITextField!

    override func viewDidLoad() {

    super.viewDidLoad()

    // Do any additional setup after loading the view.

    }

    override func didReceiveMemoryWarning() {

    super.didReceiveMemoryWarning()

    // Dispose of any resources that can be recreated.

    }

    @IBAction func registerButtonTapped(sender: AnyObject) {

    let userEmail = userEmailtextfield.text;

    let userPassword = userPasswordTextField.text;

    let userRepeatPassword = userRepeatPasswordTextField.text;

    /*let userEmail = “huzefa”;

    let userPassword = “123”;

    let userRepeatPassword = “123”;*/

    //Checking for empty textfield

    if(userEmail == “”||userPassword == “”||userRepeatPassword == “”){

    displayMyAlertMessage(“All fields are to be filled”);

    return;

    }

    /*if(userEmail.isEmpty||userPassword.isEmpty||userRepeatPassword.isEmpty)

    {

    //Display alert message

    displayMyAlertMessage(“All fields are to be filled”);

    return;

    }*/

    if(userPassword != userRepeatPassword){

    //DIsplay alert message

    displayMyAlertMessage(“Repeat Password field is not matched with Password field”);

    return;

    }

    //Send user data to the server side

    let myUrl=NSURL(string:”http://huzefa_vakharia.comxa.com/userRegister.php”);

    let request=NSMutableURLRequest(URL:myUrl!);

    request.HTTPMethod=”POST”;

    let postString=”email=(userEmail)&password=(userPassword)”;

    request.HTTPBody=postString.dataUsingEncoding(NSUTF8StringEncoding);

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

    data,response,error in

    if error != nil {

    print(“error=(error)”)

    return;

    }

    var err: NSError?

    var json = NSJSONSerialization.JSONObjectWithData(data,

    options: .MutableContainers, error: &err ) as? NSDictionary

    if let parseJSON=json{

    var resultValue=parseJSON[“status”] as?String

    println(“result:(resultValue)”)

    var isUserRegisterated:Bool=false;

    if(resultValue==”Success”){isUserRegisterated=true;}

    var messageToDisplay:String = parseJSON[“message”] as String!;

    if(!isUserRegisterated){

    messageToDisplay = parseJSON[“message”] as String!;

    }

    dispatch_async(dispatch_get_main_queue(), {

    //Display alert message with confirmation

    let myAlert = UIAlertController(title:”Alert”,message:messageToDisplay,preferredStyle: UIAlertControllerStyle.Alert);

    let okAction = UIAlertAction(title:”OK”,style:UIAlertActionStyle.Default){

    action in self.dismissViewControllerAnimated(true, completion: nil)

    }

    myAlert.addAction(okAction);

    self.presentViewController(myAlert,animated:true,completion:nil);

    });

    }

    }

    task.resume()

    }

    func displayMyAlertMessage(userMessage:String) {

    let myAlert = UIAlertController(title:”Alert”,message:userMessage,preferredStyle: UIAlertControllerStyle.Alert);

    let okAction = UIAlertAction(title:”OK”,style:UIAlertActionStyle.Default,handler: nil);

    myAlert.addAction(okAction);

    self.presentViewController(myAlert,animated:true,completion:nil);

    }

    }

    pls solve this very critical problem.

  • Huzefa Vakhariya

    Hello Kargopolov, I solved the problem of NSJSONSerialization() , using your previous discussion posted here, but now I am getting another issue i.e.:

    Error Domain=NSCocoaErrorDomain Code=3840 “JSON text did not start with array or object and option to allow fragments not set.” UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}

    So how to solve it?

    • Richard

      Hello – I am getting the same error, did you ever fix this?

  • Bishàl Gautam

    Hi I want to debug my code. Can you pease guide me where to check for the echo statements in the PHP scripts. I am using localhost.

  • Gal

    i get an error when I press register button:
    Error Domain=NSCocoaErrorDomain Code=3840 “No value.” UserInfo={NSDebugDescription=No value.}

  • Gal

    i get an error when I press register button:
    Error Domain=NSCocoaErrorDomain Code=3840 “No value.” UserInfo={NSDebugDescription=No value.}

    • Gal

      i fixed registration error, i was missing some ” in Conn.php file xD

      now i have a problem with login, i get the error below. can you help me?

  • Gal

    I can’t login. I get result: Optional(“error”). What did i do wrong? Registration works fine …

    • Gal

      I fixed my error. In the database, i didn’t have id … now it works fine.

  • Mayank Gupta

    Hi Surgey

    The Toutorial you uploaded is really very helful… But What changes do we need to make in our swift code if we want to use our own data base instead of using local storage(– USER DEFAULTS)???

  • Maciej

    Hello, thanks for Your Tutorial really helpful! <3 Can You tell me how I can get UserEmail in this app?

  • Maciej

    Hello, thanks for Your Tutorial really helpful! <3 Can You tell me how I can get UserEmail in this app?

  • blackie

    Hello! I follow the tutorial on youtube and I keep getting a Fatal error: Call to undefined method access::registerUser() on the line
    $result = $connection->registerUser($username, $secured_password, $salt, $email, $fullname);
    and
    $user = $access->selectUser($username); for selectUser
    in register.php

  • seyedmahbod tabatabaie

    Hi at first I want appreciate to your very good tutorial,I saw Your last 3 videos for sing up and login on Youtube, but I have a question and I think for you is ridiculous.
    in MySQLDao.php for example for $dbhost,$dbuser I have to use null for them? could please tell me which part of php page change?? I want write these php file exactly like you but which part need to change??? please help me

    • You do not need to change $dbhost and $dbuser values in MySQLDao.php. These values are set in Conn.php file

  • Richard

    Hi everyone – I’ve had the JSON error so have followed the instructions to test in browser and replaced POST to REQUEST in the php scripts. I think I am having trouble actually connecting to the database as I get this error:

    Warning: mysqli::mysqli() [mysqli.mysqli]: (HY000/2002): Can’t connect to local MySQL server through socket ‘/var/lib/mysql/mysql.sock’ (2) in /var/sites/q/quasisquest.uk/public_html/KeepScore/MySQLDao.php on line 21

    exception ‘Exception’ with message ‘Could not establish connection with database’ in /var/sites/q/quasisquest.uk/public_html/KeepScore/MySQLDao.php:23 Stack trace: #0 /var/sites/q/quasisquest.uk/public_html/KeepScore/userRegister.php(20): MySQLDao->openConnection() #1 {main}

    Thanks everyone!

    • Hi Richard! Did you figure out the problem?

      • Richard

        Hi Serge, I never. Have you had chance to look at the file I emailed you?

        Someone off StackOverflow gave a solution but it just wiped out the AppDelegate function that removed the Protected Page when logging in. 🙁

        • Sorry! For some reason messages from comments don’t get delivered to be right away… When test the code via the browser window. Can you print user name is password? Just want to make sure your PHP code does actually have them..

      • Richard

        Sorry Serge, I’ve just realised your question was relating to the JSON error and not the one I emailed you about!

  • Fatih Köroğlu

    Hi, Thanks for this sample Kargopolov.
    I’am using Swift 3 and somewhere has changed. This code is working and have to add this code info.plist
    //info.plist code
    NSAppTransportSecurity

    NSAllowsArbitraryLoads

    NSExceptionDomains

    http://www.fatihkoroglu.info/

    NSIncludesSubdomains

    NSThirdPartyExceptionRequiresForwardSecrecy

    // RegisterViewController.swift
    // Login System
    //
    // Created by fatih köroğlu on 1.11.2016.
    // Copyright © 2016 was here. All rights reserved.
    //

    import UIKit

    class RegisterViewController: UIViewController {
    @IBOutlet var userEmailTF: UITextField!
    @IBOutlet var userPassTF: UITextField!
    @IBOutlet var userRePassTF: UITextField!

    override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
    }

    @IBAction func registerButton(_ sender: AnyObject) {

    let userEmail = userEmailTF.text;
    let userPass = userPassTF.text;
    let userRepass = userRePassTF.text;

    if (userEmail?.isEmpty)! || (userPass?.isEmpty)! || (userRepass?.isEmpty)! {

    displayAlertMesaage(userMessage: “Boş Bırakılan Alan Bro..”)

    return;

    }

    if userRepass != userPass {
    displayAlertMesaage(userMessage: “Şifreler Eşleşmiyor Bro”)
    }

    /* UserDefaults.standard.set(userEmail, forKey: “userEmail”);
    UserDefaults.standard.set(userPass, forKey: “userPass”);
    UserDefaults.standard.set(userRepass, forKey: “userRepass”);
    UserDefaults.standard.synchronize() */

    let myUrl=NSURL(string:”http://www.fatihkoroglu.info/user-register/userRegister.php”);

    //let request=NSMutableURLRequest(URL:myUrl!);
    let request = NSMutableURLRequest(url: myUrl! as URL)

    //request.HTTPMethod=”POST”;
    request.httpMethod = “POST”;

    let postString=”email=(userEmail!)&password=(userPass!)”;

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

    let task = URLSession.shared.dataTask(with: request as URLRequest) {

    data, response, error in

    if error != nil {

    print(“error=(error)”)

    return

    }

    do {

    let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary

    if let parseJSON = json {

    let resultValue = parseJSON[“status”] as! String!

    print(“result: (resultValue)”)

    var isUserRegistered: Bool = false

    if (resultValue == “Success”) {

    isUserRegistered = true

    }

    var messageToDisplay: String = parseJSON[“message”] as! String!

    if (!isUserRegistered)

    {

    messageToDisplay = parseJSON[“message”] as! String!

    }

    DispatchQueue.main.async {

    let myAlert = UIAlertController(title: “Uyarı”, message: messageToDisplay, preferredStyle: UIAlertControllerStyle.alert)

    let okAction = UIAlertAction(title: “Tamam”, style: UIAlertActionStyle.default) { action in

    self.dismiss(animated: true, completion: nil)

    }

    myAlert.addAction(okAction)

    self.present(myAlert, animated: true, completion: nil)

    }

    }

    } catch { print(error)}

    }

    task.resume()

    }

    func displayAlertMesaage(userMessage:String)
    {

    let myAlert = UIAlertController(title: “Uyarı”, message: userMessage, preferredStyle: UIAlertControllerStyle.alert);

    let okAction = UIAlertAction(title: “Tamam”, style: UIAlertActionStyle.default, handler: nil)
    myAlert.addAction(okAction);

    self.present(myAlert, animated: true, completion: nil)

    }

    }

    • ridwan

      sory

    • negar Tolou

      hi can u post loginviewControler in swift3? plz!

  • ridwan

    sergey I want to ask something to you.

    when I enter a username and password and press enter, go well.

    but when the username and password are not in the content and then pressed login button, even into the menu, and no error message

    I query whether there is something wrong.
    i use this query :
    @IBAction func signinButton(_ sender: AnyObject) {
    self.ActivityIndicator.startAnimating()

    let AU_ID = usernameTextField.text;
    let AU_Pwd = passwordTextField.text;

    if (AU_ID!.isEmpty || (AU_Pwd!.isEmpty)){
    let alert = UIAlertController(title: “Information!”, message: “Username and Password is not empety”, preferredStyle: UIAlertControllerStyle.alert)
    alert.addAction(UIAlertAction(title: “Dismiss”, style: UIAlertActionStyle.destructive, handler: nil))
    present(alert, animated: true, completion: nil)
    self.present(alert, animated: true, completion: nil)
    }

    //send user data to server side
    let myUrl = URL(string:”http://xx.xxx.x.x/phmis/userLogin.php”);
    let request = NSMutableURLRequest(url:myUrl!);
    request.httpMethod = “POST”;

    let postString = “AU_ID=(AU_ID!)&AU_Pwd=(AU_Pwd!)”;

    request.httpBody = postString.data(using: String.Encoding.utf8);
    let task = URLSession.shared.dataTask(with: request as URLRequest){
    (data, response, error) in

    if error != nil {
    print(“error=(error)”)
    return
    }

    do {
    let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary

    if let parseJSON = json{

    let resultValue:String = parseJSON[“status”] as! String!;
    print(“result: (resultValue)”)

    if(resultValue == “Success”)
    {
    //Get au_id
    let prefs:UserDefaults = UserDefaults.standard
    prefs.set(AU_ID, forKey: “USERNAME”)
    prefs.set(1, forKey: “ISLOGGEDIN”)
    prefs.synchronize()

    DispatchQueue.main.async(execute: {
    self.dismiss(animated: false, completion: {})
    self.performSegue(withIdentifier: “loginView”, sender: nil)
    })
    }else {
    if parseJSON[“error”] as? String != nil {
    self.message = parseJSON[“error”] as! String
    } else {
    DispatchQueue.main.async(execute: {
    let importantAlert: UIAlertController = UIAlertController(title: “Information!”, message: “Username and Password is do not match”, preferredStyle: .alert) //ActionSheet
    let defaultAction = UIAlertAction(title: “Dismiss”, style: .destructive, handler: nil)
    importantAlert.addAction(defaultAction)
    self.present(importantAlert, animated: true, completion: nil)
    self.ActivityIndicator.stopAnimating()
    })
    }
    }
    }
    } catch {
    print(error)
    }
    };
    task.resume()
    }

  • Ashish Awasthi

    Hi.
    I have a doubt regarding your topic (Store user information in MySQL database). As you are doing this using PHP and My SQL database. Can I store user information in MS SQL server database using ASP.NET c#. Please show one example.

    Thank you in advance.