Skip to content

iOS Login and Signup Screen tutorial : Swift + XCode 6 + iOS 8 + JSON

This tutorial will guide you to create a simple app with a Signup and Login screen which takes username and password from the user and then posts it to an url and parse the JSON response. We will have three view controllers for this project, Signup, Login and Home.

Updated for 2026: this tutorial is from 2014 and its server scripts are no longer online. For a current version built with SwiftUI, Face ID and a PHP 8 API, see SwiftUI Login and Signup Screen tutorial (2026).

This tutorial will guide you to create a simple app with a Signup and Login screen which takes username and password from the user and then posts it to an url and parse the JSON response.

We will have three view controllers for this project, Signup, Login and Home.

  1. Create a New project. And add the Screens and Segues/transitions.
  2. Home – Check for an existing session, else goto Login
  3. Login Screen – Post data to URL and parse the JSON response.
  4. Signup Screen – Post data to URL and parse the JSON response.
  5. Add Logout to Home Screen

xcode6 swfit login tutorial storyboard

1. Create a New project. And add the Screens and the Segue/transition.

I had issues with Xcode 6.1, not allowing me to create segue between View Controllers. Please see this video for an alternative way to do that:

2. Create Classes Properties And Methods:

Add code to viewDidAppear of HomeVC.swift
to check for existing login, if no session is found then show the login screen.

override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(true)
 
        let prefs:NSUserDefaults = NSUserDefaults.standardUserDefaults()
        let isLoggedIn:Int = prefs.integerForKey("ISLOGGEDIN") as Int
        if (isLoggedIn != 1) {
            self.performSegueWithIdentifier("goto_login", sender: self)
        } else {
            self.usernameLabel.text = prefs.valueForKey("USERNAME") as NSString
        }
    }

signupTapped in SignupVC.swift:

@IBAction func signupTapped(sender : UIButton) {
        var username:NSString = txtUsername.text as NSString
        var password:NSString = txtPassword.text as NSString
        var confirm_password:NSString = txtConfirmPassword.text as NSString
 
        if ( username.isEqualToString("") || password.isEqualToString("") ) {
 
            var alertView:UIAlertView = UIAlertView()
            alertView.title = "Sign Up Failed!"
            alertView.message = "Please enter Username and Password"
            alertView.delegate = self
            alertView.addButtonWithTitle("OK")
            alertView.show()
        } else if ( !password.isEqual(confirm_password) ) {
 
            var alertView:UIAlertView = UIAlertView()
            alertView.title = "Sign Up Failed!"
            alertView.message = "Passwords doesn't Match"
            alertView.delegate = self
            alertView.addButtonWithTitle("OK")
            alertView.show()
        } else {
 
            var post:NSString = "username=\(username)&password=\(password)&c_password=\(confirm_password)"
 
            NSLog("PostData: %@",post);
 
            var url:NSURL = NSURL(string: "https://dipinkrishna.com/jsonsignup.php")!
 
            var postData:NSData = post.dataUsingEncoding(NSASCIIStringEncoding)!
 
            var postLength:NSString = String( postData.length )
 
            var request:NSMutableURLRequest = NSMutableURLRequest(URL: url)
            request.HTTPMethod = "POST"
            request.HTTPBody = postData
            request.setValue(postLength, forHTTPHeaderField: "Content-Length")
            request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
            request.setValue("application/json", forHTTPHeaderField: "Accept")
 
 
            var reponseError: NSError?
            var response: NSURLResponse?
 
            var urlData: NSData? = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error:&reponseError)
 
            if ( urlData != nil ) {
                let res = response as NSHTTPURLResponse!;
 
                NSLog("Response code: %ld", res.statusCode);
 
                if (res.statusCode >= 200 && res.statusCode < 300)
                {
                    var responseData:NSString  = NSString(data:urlData!, encoding:NSUTF8StringEncoding)!
 
                    NSLog("Response ==> %@", responseData);
 
                    var error: NSError?
 
                    let jsonData:NSDictionary = NSJSONSerialization.JSONObjectWithData(urlData!, options:NSJSONReadingOptions.MutableContainers , error: &error) as NSDictionary
 
 
                    let success:NSInteger = jsonData.valueForKey("success") as NSInteger
 
                    //[jsonData[@"success"] integerValue];
 
                    NSLog("Success: %ld", success);
 
                    if(success == 1)
                    {
                        NSLog("Sign Up SUCCESS");
                        self.dismissViewControllerAnimated(true, completion: nil)
                    } else {
                        var error_msg:NSString
 
                        if jsonData["error_message"] as? NSString != nil {
                            error_msg = jsonData["error_message"] as NSString
                        } else {
                            error_msg = "Unknown Error"
                        }
                        var alertView:UIAlertView = UIAlertView()
                        alertView.title = "Sign Up Failed!"
                        alertView.message = error_msg
                        alertView.delegate = self
                        alertView.addButtonWithTitle("OK")
                        alertView.show()
 
                    }
 
                } else {
                    var alertView:UIAlertView = UIAlertView()
                    alertView.title = "Sign Up Failed!"
                    alertView.message = "Connection Failed"
                    alertView.delegate = self
                    alertView.addButtonWithTitle("OK")
                    alertView.show()
                }
            }  else {
                var alertView:UIAlertView = UIAlertView()
                alertView.title = "Sign in Failed!"
                alertView.message = "Connection Failure"
                if let error = reponseError {
                    alertView.message = (error.localizedDescription)
                }
                alertView.delegate = self
                alertView.addButtonWithTitle("OK")
                alertView.show()
            }
        }
 
    }

signinTapped in LoginVC.swift:

@IBAction func signinTapped(sender : UIButton) {
        var username:NSString = txtUsername.text
        var password:NSString = txtPassword.text
 
        if ( username.isEqualToString("") || password.isEqualToString("") ) {
 
            var alertView:UIAlertView = UIAlertView()
            alertView.title = "Sign in Failed!"
            alertView.message = "Please enter Username and Password"
            alertView.delegate = self
            alertView.addButtonWithTitle("OK")
            alertView.show()
        } else {
 
            var post:NSString = "username=\(username)&password=\(password)"
 
            NSLog("PostData: %@",post);
 
            var url:NSURL = NSURL(string: "https://dipinkrishna.com/jsonlogin2.php")!
 
            var postData:NSData = post.dataUsingEncoding(NSASCIIStringEncoding)!
 
            var postLength:NSString = String( postData.length )
 
            var request:NSMutableURLRequest = NSMutableURLRequest(URL: url)
            request.HTTPMethod = "POST"
            request.HTTPBody = postData
            request.setValue(postLength, forHTTPHeaderField: "Content-Length")
            request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
            request.setValue("application/json", forHTTPHeaderField: "Accept")
 
 
            var reponseError: NSError?
            var response: NSURLResponse?
 
            var urlData: NSData? = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error:&reponseError)
 
            if ( urlData != nil ) {
                let res = response as NSHTTPURLResponse!;
 
                NSLog("Response code: %ld", res.statusCode);
 
                if (res.statusCode >= 200 && res.statusCode < 300)
                {
                    var responseData:NSString  = NSString(data:urlData!, encoding:NSUTF8StringEncoding)!
 
                    NSLog("Response ==> %@", responseData);
 
                    var error: NSError?
 
                    let jsonData:NSDictionary = NSJSONSerialization.JSONObjectWithData(urlData!, options:NSJSONReadingOptions.MutableContainers , error: &error) as NSDictionary
 
 
                    let success:NSInteger = jsonData.valueForKey("success") as NSInteger
 
                    //[jsonData[@"success"] integerValue];
 
                    NSLog("Success: %ld", success);
 
                    if(success == 1)
                    {
                        NSLog("Login SUCCESS");
 
                        var prefs:NSUserDefaults = NSUserDefaults.standardUserDefaults()
                        prefs.setObject(username, forKey: "USERNAME")
                        prefs.setInteger(1, forKey: "ISLOGGEDIN")
                        prefs.synchronize()
 
                        self.dismissViewControllerAnimated(true, completion: nil)
                    } else {
                        var error_msg:NSString
 
                        if jsonData["error_message"] as? NSString != nil {
                            error_msg = jsonData["error_message"] as NSString
                        } else {
                            error_msg = "Unknown Error"
                        }
                        var alertView:UIAlertView = UIAlertView()
                        alertView.title = "Sign in Failed!"
                        alertView.message = error_msg
                        alertView.delegate = self
                        alertView.addButtonWithTitle("OK")
                        alertView.show()
 
                    }
 
                } else {
                    var alertView:UIAlertView = UIAlertView()
                    alertView.title = "Sign in Failed!"
                    alertView.message = "Connection Failed"
                    alertView.delegate = self
                    alertView.addButtonWithTitle("OK")
                    alertView.show()
                }
            } else {
                var alertView:UIAlertView = UIAlertView()
                alertView.title = "Sign in Failed!"
                alertView.message = "Connection Failure"
                if let error = reponseError {
                    alertView.message = (error.localizedDescription)
                }
                alertView.delegate = self
                alertView.addButtonWithTitle("OK")
                alertView.show()
            }
        }
 
    }

logoutTapped in HomeVC.swift

 @IBAction func logoutTapped(sender : UIButton) {
 
        let appDomain = NSBundle.mainBundle().bundleIdentifier
        NSUserDefaults.standardUserDefaults().removePersistentDomainForName(appDomain!)
 
        self.performSegueWithIdentifier("goto_login", sender: self)
    }

Checkout the end result of the tutorial:

Download the full source code using the link below:

It contains the xcode project, php code and the sql file for the whole project.

Xcode Project : Swift Login/Signup App
Xcode 7 Beta Project : Swift Login/Signup App – Xcode 7 Beta
Php Code : SwiftJsonLoginPHP.zip

Thanks, Hope it helps!

Dipin Krishna

Written by Dipin Krishna

Senior full-stack engineer with 15 years across Django, Laravel, SwiftUI and the infrastructure underneath. Available for contract work.

Work with me β†’

140 comments

  1. Hi,
    can you specify what u mean by β€œuse our own data base instead of using local storage(USER DEFAULTS)”?
    Are you try to save the data in a local DB within the app instead of user defaults?

  2. Hi Rob,

    I am creating a tutorial for Login/Signup + auto login using touch id.
    But, it on Xcode 8 + objective C.
    I will try to add swift code too.

    Thanks.

  3. Hi Dipin,
    Many thanks for this excellent tutorial.
    Is it possible to update it for Xcode version 7.3.1?

  4. i got an error when i tried to log in
    fatal error: unexpectedly found nil while unwrapping an Optional value
    xcode show green line at: var lastname:NSString = jsonData[“email”] as! NSString

  5. You need to pass the info you need in the JSON reply during login.
    Then parse the json and save it in the NSUserDefaults.

    Eg:

    var firstname:NSString = jsonData["firstname"] as NSString
    var lastname:NSString = jsonData["lastname"] as NSString
    var prefs:NSUserDefaults = NSUserDefaults.standardUserDefaults()
    prefs.setObject(username, forKey: "USERNAME")
    prefs.setObject(firstname, forKey: "FNAME")
    prefs.setObject(lastname, forKey: "LNAME")
    prefs.setInteger(1, forKey: "ISLOGGEDIN")
    prefs.synchronize()

    Hope it helps!

  6. Helo!
    I have one more column named email, how can i show user’s email when user login? And how to store all user’s information to NSUserDefaults with email, firstname, lastname, age…

  7. I keep getting this error: fatal error: “unexpectedly found nil while unwrapping an Optional value”

    It is on this line of the code:

    “let jsonData:NSDictionary = NSJSONSerialization.JSONObjectWithData(urlData!, options:NSJSONReadingOptions.MutableContainers , error: &error) as! NSDictionary”

  8. Hey there,

    For whatever reason, no matter what I do whenever I create an account (with what I’m sure are unique usernames), it always says “username exists”.

    2015-08-05 14:01:52.746 PING[53354:2853979] Response code: 200
    2015-08-05 14:01:52.746 PING[53354:2853979] Response ==> {“success”:0,”error_message”:”Username Exist.”}
    2015-08-05 14:01:52.756 PING[53354:2853979] Success: 0

    I’m using Xcode 6 with iOS 8

    Any suggestions?

  9. Hi Dipin,

    I always get connection error when trying to connect to localhost php. I am using Xcode 7 beta.

    Let me know if any settings I need to apply to make it work ?

    Regards,
    Raghu

  10. Hi, I am wondering how to link the PHP file to the actual app, mine says error: username already exists even though it is completely random! Any help!

  11. Hey Keyur,

    1. Run the sql file.
    2. Create a new user/pass for the DB or you can use the root user.
    3. Update the DB host, username and password in the php files.
    4. Update the url in the swift code.

    That should do.

    Thanks.

  12. Thanks for the tutorial… one thing– I want to go ahead and make my own MySQL database to implement this system myself–still on a developmental standpoint.

    What all do I need to do (new to databases)?

    Do I need to change anything in the .php files you attached?
    In the code, do I just need to change the URL’s which link to your website and to mine?

    Thanks

  13. This is great stuff. Didn’t use the entire code base but used it to find a problem in my own. I’m new to Swift, it really helped me out!

  14. hi im trying to use your db in my web and i get this error

    2015-07-06 18:00:20.324 SwiftLoginScreen[880:32379] PostData: username=qwe&password=qwe&c_password=qwe
    2015-07-06 18:00:21.813 SwiftLoginScreen[880:32379] Response code: 200
    2015-07-06 18:00:21.813 SwiftLoginScreen[880:32379] Response ==>
    Warning: mysqli::mysqli(): (28000/1045): Access denied for user ‘DB_USER’@’10.2.1.48’ (using password: YES) in /home/u342872465/public_html/jsonsignup.php on line 21
    {“success”:0,”error_message”:”Access denied for user ‘DB_USER’@’10.2.1.48’ (using password: YES)”}
    fatal error: unexpectedly found nil while unwrapping an Optional value
    (lldb)

    what happen with this? please help me

  15. Hello, I downloaded the source code and ran it from simulator and my iPhone and when I tap on the sing up button and sign up it brings up a popup menu saying Username Exist, why?

    Thank you,

    Rogelio

  16. hi, your tutorial is amazing it helps me a lot.
    i am new in xcode and swift and wanted to have more tutorial.
    i want to know how can we make feed like facebook ios app.
    also after login success i wanted to redirect to new viewcontroller so how will i achieve it.please guide.

  17. Thank you so much for fixing the errors in the latest version. It helped me out sooooooooo much! Thank you again!

  18. I am very new to ios/swift from android background and is given a very short deadline keeping my job on stake.
    I am Struck at
    let res = response as NSHTTPURLResponse;
    where it gives error
    NSURLResponse? is not convertible to NSHTTPURLResponse;
    did you mean to use ‘as!’ force downcast.

    when i downcast response, it asks me to do it again at 4 different places again until my code settles. But then , when i run my code it to fetch String from a key value pair , it gives me some ridiculous random Integer. Please help me brother. I know my question may be stupid. Sorry to bother bro, but this job is my family’s bread n butter πŸ™

  19. Thanks for the tutorial!
    When I open this file (I have not made any modifications to the file) it says that there are 7 errors. I am using Xcode 6.3.2 (not a beta version).

    The errors are:

    Objective-C method ‘application:didFinishLaunchingWithOptions:’ provided by method ‘application(_:didFinishLaunchingWithOptions:)’ conflicts with optional requirement method ‘application(_:didFinishLaunchingWithOptions:)’ in protocol ‘UIApplicationDelegate’

    ‘NSString’ is not implicitly convertible to ‘String’; did you mean to use ‘as’ to explicitly convert?

    ‘AnyObject?’ is not convertible to ‘NSString’; did you mean to use ‘as!’ to force downcast?

    ‘NSString’ is not implicitly convertible to ‘String’; did you mean to use ‘as’ to explicitly convert?

    ‘NSURLResponse?’ is not convertible to ‘NSHTTPURLResponse!’; did you mean to use ‘as!’ to force downcast?

    ‘NSString’ is not implicitly convertible to ‘String’; did you mean to use ‘as’ to explicitly convert?

    ‘NSURLResponse?’ is not convertible to ‘NSHTTPURLResponse!’; did you mean to use ‘as!’ to force downcast?

    Any ideas how to fix these errors?

  20. When I open it in Xcode 6.3.2 it gives me 5 errors! I haven’t changed anything in the file. I am also not using a beta version of Xcode. I am getting errors like:

    ‘NSString’ is not implicitly convertible to ‘String’; did you mean to use ‘as’ to explicitly convert?

    ‘NSURLResponse?’ is not convertible to ‘NSHTTPURLResponse!’; did you mean to use ‘as!’ to force downcast?

    ‘AnyObject?’ is not convertible to ‘String’; did you mean to use ‘as!’ to force downcast?

    ‘NSString’ is not implicitly convertible to ‘String’; did you mean to use ‘as’ to explicitly convert?

    ‘NSURLResponse?’ is not convertible to ‘NSHTTPURLResponse!’; did you mean to use ‘as!’ to force downcast?

    Any ideas how to fix these errors?

  21. thanks for the tutorials
    hey can you continue your series by adding more tutorials like user profile or something like that

  22. thanks sir, it worked perfectly
    can you continue your series by adding more tutorials like user profile or something like that
    thanks

  23. Hi Dipin,

    I have tried to update the if statement to if(isset[$_POST]) but to no avail. Where exactly am I missing the &

    header(‘Content-type: application/json’);
    if($_POST) {
    $username = $_POST[‘username’];
    $password = $_POST[‘password’];
    $c_password = $_POST[‘confirmPassword’];

    if($_POST[‘username’]) { //if ($username && $password == $c_password) also doesnt work
    if ( $password == $c_password ) {

    $db_name = ‘laundryMembers’;
    $db_user = ‘root’;
    $db_password = ‘root’;
    $server_url = ‘localhost’;

  24. Here is the php log. Is it something to do with the undefined index?

    [19-Apr-2015 01:51:02 Europe/Berlin] Success: 1
    [19-Apr-2015 01:51:02 Europe/Berlin] User ‘1password=1confirmPassword=1’ created.
    [19-Apr-2015 01:51:39 Europe/Berlin] User 1: password doesn’t match.
    [19-Apr-2015 01:51:48 Europe/Berlin] PHP Notice: Undefined index: password in /Applications/MAMP/htdocs/jsonsignup.php on line 10
    [19-Apr-2015 01:51:48 Europe/Berlin] PHP Notice: Undefined index: confirmPassword in /Applications/MAMP/htdocs/jsonsignup.php on line 11
    [19-Apr-2015 01:51:48 Europe/Berlin] Success: 1
    [19-Apr-2015 01:51:48 Europe/Berlin] User ‘2password=2confirmPassword=2’ created.
    [19-Apr-2015 02:20:14 Europe/Berlin] User 1: password doesn’t match.
    [19-Apr-2015 02:20:48 Europe/Berlin] User 1: password doesn’t match.
    [19-Apr-2015 02:20:56 Europe/Berlin] PHP Notice: Undefined index: password in /Applications/MAMP/htdocs/jsonsignup.php on line 10
    [19-Apr-2015 02:20:56 Europe/Berlin] PHP Notice: Undefined index: confirmPassword in /Applications/MAMP/htdocs/jsonsignup.php on line 11
    [19-Apr-2015 02:20:56 Europe/Berlin] Success: 1
    [19-Apr-2015 02:20:56 Europe/Berlin] User ‘112password=112confirmPassword=112’ created.
    [19-Apr-2015 02:21:26 Europe/Berlin] User 112: password doesn’t match.

  25. Hi,

    Great tutorial! I am having an issue. After I sign up, I am not able to login with the same username/password. The username and password are created in the database successfully. Is it something to do with collation at phpmyAdmin? Can you please help.

    2015-04-18 20:35:59.722 LaundryTimer[4967:109617] Sucess: 1
    2015-04-18 20:35:59.722 LaundryTimer[4967:109617] Sign Up Success
    2015-04-18 20:36:02.611 LaundryTimer[4967:109617] PostData: username=12&password=12
    2015-04-18 20:36:02.615 LaundryTimer[4967:109617] Response code: 200
    2015-04-18 20:36:02.615 LaundryTimer[4967:109617] Response ==> {“success”:0,”error_message”:”Invalid Username/Password”}
    2015-04-18 20:36:02.616 LaundryTimer[4967:109617] Success: 0

  26. When trying to log in, I get an error saying A server with the specified hostname could not be found. I have changed the URL in the Swift code and changed the PHP file as much as I thought needed (DB name, username and password). Can you help at all?

  27. Hey,

    Can you make sure mysql is running?

    mysqladmin -u root -p status

    If its running, can you verify in my.cnf that socket file is set to ‘/var/lib/mysql/mysql.sock’.

    socket=/var/lib/mysql/mysql.sock

    Please check the permissions also:

    sudo chmod -R 777 /var/lib/mysql/

    Thanks.

  28. So i have made my own mysql database and uploaded the two php to my website and changed all the login credentials to fit my database and set the url to the one that directs to my site (php) in loginvc and signupvc but as soon as i run the emulator for the app and hit register for signup i get cant connect to local MySql server through socket ‘/var/lib/mysql/mysql.sock’ (2).

  29. hello!
    First I want to thank you for this tutorial.
    I would like to ask you why when vao to login or sign up to me this error:
    “Access denied for user ‘json_login1 @ localhost’ (using password: YES).
    Thanks for the possible response

  30. You can use NSUserDefaults to store the info, during login.
    I already save the username in userdefaults.

    prefs.setObject(username, forKey: "USERNAME")

    Then later when they return, fill the login screen with the info from userdefaults.

  31. Hi dipin sir,
    I am new to xcode. I want to create login screen with Remember me check box where it stores Username and password .Please guide me ThaksIn advance !!!

  32. Hi

    Your tutorial was really helpful for me as it shows how to create outlet just by ctrl dragging from the UI controls. But i was trying to create one simple app which has gesture init.I dragged swipe gesture on my view and tried to create outlet as u shown in video by ctrl dragging from it on the view controller file in assistant editor.
    But i could not .
    I saw other tutorials too where they have used one more UIView for the sake of gesture. But again they were writing IBOutlet manually in editor. So i was thinking if one can really create IBOutlet and IBAction by ctrl dragging from swipe gesture onto the editor file?

  33. Hey,

    Its easy, you will have to pass the first name in the json reply during authentication.
    Parse it on the app side, store it in userdefaults/coredata.
    When you are on the Home screen retrieve it from where you have saved it and display it.

    Thanks.

  34. Great tutorial!! Thanks a lot for this. IΒ΄m new in swift… and i was wondering, how it would be your approach in the case i want to show other data in the home label , for example, i connected your code to an existent mysql database, and it has a “firstname” table… well, instead of showing the Username like in your tutorial, i want to show the “firstname” of the database. Thanks.

  35. Awesome tutorial! This was my first tutorial using swift and XCode and found it very useful especially the navigation of the XCode UI, wiring up the events, properties, and story board. Thanks!

  36. Fixed the problem. md5 in this line was the problem: $stmt->bind_param(β€œss”, $username, md5($password));

    So i did this instead:

    $userpass=md5($password);
    $stmt->bind_param(“ss”, $username, $userpass);

    and worked. Not sure why if in you online jsonlogin2.php works…

    Thanks.

  37. This is the line 29.. $stmt->bind_param(“ss”, $username, md5($password));

    Its the same than on your file… i didnΒ΄t touch anything there…. Thats why i donΓ±t get why it doesnΒ΄t work in my server.. Thanks.

  38. This is the response from your server:

    <br />
    <b>Strict Standards</b>:  Only variables should be passed by reference in <b>/home/digidevs/public_html/projects/fbpcompanion/jsonlogin2.php</b> on line <b>29</b><br />
    {"success":1}
  39. Thanks for your quick reply. Yes, i tried again, and i received the same error…
    I signed up using my server and it worked perfect, the problem is with login… are you sure the file jsonlogin2.php i downloaded yesterday is the same than in https://dipinkrishna.com/jsonlogin2.php ? because as i said, when i used your url works, but when i change it to my server at var url:NSURL = NSURL(string: “http://digidevs.com/projects/fbpcompanion/jsonlogin2.php”)! i got the error…

    Could be something related to my server configuration? Thanks a lot!

  40. Everything works geat when i use your php files, in your server, but when i used on mine, i got : fatal error: unexpectedly found nil while unwrapping an Optional value and this part highlighted in green…

    let jsonData:NSDictionary = NSJSONSerialization.JSONObjectWithData(urlData!, options:NSJSONReadingOptions.MutableContainers , error: &error) as NSDictionary

    what can it be? Thanks.

  41. hi, I tried this and copied everything etc from the downloadable source code but for some reason when i lunch the app, it stays on the home page even though there is not a login session. how can i fix this? there are no errors whats so ever.

  42. Ok, So i got it working. I forgot to remove the old button references i made when watching your tutorial when i pasted over them with your codes above. I have everything working fine now. This tutorial is amazing!

    My question now is. When i develop my application, i would like to manage the users account. Is it possible to implement Parse to hold the data?

  43. Hey, So i the codes working pefectly besides he create account part. In the simulator it gives me an error when i try to create an account. I would assume is because its using your PHP. How do i create my own and get it working?

  44. Dipin

    Thanks a lot for this tutorial, I am just starting out (not in life, just in coding) and it is great.

    Thanks again!

  45. Hello,
    Thanks for your feedbacK;
    ok, so basically the main view controller is the HomeVC and then you check if the user is already signed in to go to the LoginVC if he is not ?
    Luc

  46. I got this working by making another segue from the login screen to the signed in screen and flipping the process, meaning the app starts on the sign in screen but if the user is signed in it uses the new segue without animation to immediately show the signed in screen – otherwise it just shows the login screen.

    Using a separate segue from the original login to signin segue means you can still keep the animation when the user hits the sign in button.

    Hope this helps!

  47. Exactly what I was looking for!

    Thanks so much, I’m making my first app in Swift and have been thrown in right at the deep end – so this was incredibly helpful!

    Thanks again πŸ™‚

  48. Hi
    i CREATE TABLE and change this

    var url:NSURL = NSURL(string:”https://dipinkrishna.com/jsonlogin2.php”)!
    to
    var url:NSURL = NSURL(string:”http://MYSERVERIP/jsonlogin2.php”)!

    and the php

    $mysqli = new mysqli(‘localhost’, $db_user, $db_password, $db_name);
    to
    $mysqli = new mysqli(‘localhost’, ‘root’, ‘111111’, ‘users_ios’);

    but still could not connect to the server
    What I need to change
    plz help
    thank you

  49. Hey,
    You can take care of that from the server side.
    May be you want to show the user a message like : “We will inform you when your application is accepted.”
    And send an email when you authorize the registration.

  50. Hi,
    Is it possible to manage users – delete a user, add a user etc – in the back end.
    Or maybe have it in a way, the user registers but in the backend has to be accepted / authorised to login.

  51. Hi!

    Great post, great job, thanks a lot!

    I’m trying to improve, from sign up view to home view when a user has created an account and refresh home view with new user.

    I think this code:
    var prefs:NSUserDefaults = NSUserDefaults.standardUserDefaults()
    prefs.setObject(username, forKey: “USERNAME”)
    prefs.setInteger(1, forKey: “ISLOGGEDIN”)
    prefs.synchronize()

    and dismiss login view modal when Sign up success.

    If I get this, I’ll post….

    Bye

  52. and

    var url:NSURL = NSURL.URLWithString(“https://dipinkrishna.com/jsonlogin2.php”)

    in signinTapped

  53. I have one error

    var url:NSURL = NSURL.URLWithString(“https://dipinkrishna.com/jsonsignup.php”)

    in signupTapped

    I don’t know how to fix it, please help

    Thanks a lot

  54. Hi Krishna,
    do you think it’s possible to check the credential in the appDelegate and select a rootviewcontroller (HomeViewController or LoginViewController) at this location ?

  55. Hi, I was reviewing the code and worked perfectly, unfortunately in the new update of Xcode, it marks error in this line “NSURL.URLWithString” inside “LoginVC” apparently that command is no longer available, try to fix it with other functions “NSURL “did not work. What do you think will replace command? thank you

  56. Thanks.
    Otherwise, is this possible to call the “goto_login” segue from another method than viewDidAppear ? I tried with viewWillAppear but this is not working either.

  57. Hi Luc,

    You can insert a screen before the home screen, make it something like a “loading” screen, and have it check the login session and make the redirections.

  58. Hi,
    thanks this is a great tutorial.
    I’ve just noticed the Home view is visible a fraction of second before the login views is presented. Is there a way to go directly to the login view without seeing the Home view in the case the user is not identified ?
    Thanks a lot,
    Luc

  59. Thank you for this tutorial.
    I’m using Xcode 6.1 and i got an error: ” UrlWithString is unavailable use object construction”
    Can you help me please.

  60. Thanks dude, I’m from malaysia and doing FYP current year. It helps me a lot. New to iOS apps πŸ™‚

  61. But Error was coming…”Expected Identifier in class declaration”
    Plz give any solution

  62. The post request was not successful. (It can be due to many reason, non existing api in your case).
    So, the sendSynchronousRequest was returning nil.
    The source code has been updated to catch this scenario.

  63. I fixed it by changing the code to this

    var post:NSString = “session[email]=\(email)&session[password]=\(password)”

    I was actually trying to connect to my own API, which could be another reason why it wasn’t working. Thanks though. Great tutorial. Keep em Coming πŸ™‚

  64. The error starts at this line of code and it’s highlighted in GREEN
    NSLog(“Response code: %ld”, res.statusCode);
    and it states:
    Thread 1: EXC_BAD_INSTRUCTION (code=EXC_1386_INVoP, subcode=0x0)

  65. For some reason, this code does not work with iOS 8 and Xcode 6….I keep getting this fatal error: unexpectedly found nil while unwrapping an Optional value

  66. Thanks for this! It seems I can’t connect my Home screen to my login screen unless I create a button or something to drag from. If I just control drag from the screen, it won’t let me create a connection. Do you have any suggestion?

  67. Hi!
    It’s a great tutorial, but with the Xcode 6 beta 6 don’t works, a lot errors in the code.

    Thanks!

  68. Because of the update with Xcode 6 Beta 5, you’ve got to remember to add “!= nil” in the if statements. Optionals don’t conform to the BooleanType protocol anymore, so you can’t use them in place of boolean expressions anymore.

    GREAT source code! Excited for the explanation! MORE SWIFT PLEASE!

  69. Thanks David, that fixed it, I am still in the learning phase.

    Dipin how can I access iOS: Linea Pro tutorial – Scan Barcode?

    Will the code be explained as part of the tutorial?

    Thanks all!

  70. Look at my comment above for the fix…it’s very easy. Simply add “!= nil” after “as? NSString” in your if statements where the issues are.

  71. Getting error: “Type ‘NSString?’ does not conform to protocol ‘BooleanType.Protocol’ “

Leave a note

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.