Skip to content

iOS Login and Signup Screen tutorial : Swift 2 + XCode 7 + iOS 9 + 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.

Updated for 2026: this tutorial is from 2015 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. Its the same previous tutorial for Swift + Xcode 6, but the source code has been updated to Swift 2 using XCode 7 beta.
I will update the videos as needed.

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? String
        }
    }

signupTapped in SignupVC.swift:

@IBAction func signupTapped(sender : UIButton) {
        let username:NSString = txtUsername.text!
        let password:NSString = txtPassword.text!
        let confirm_password:NSString = txtConfirmPassword.text!
 
        if ( username.isEqualToString("") || password.isEqualToString("") ) {
 
            let 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) ) {
 
            let alertView:UIAlertView = UIAlertView()
            alertView.title = "Sign Up Failed!"
            alertView.message = "Passwords doesn't Match"
            alertView.delegate = self
            alertView.addButtonWithTitle("OK")
            alertView.show()
        } else {
            do {
 
                let post:NSString = "username=\(username)&password=\(password)&c_password=\(confirm_password)"
 
                NSLog("PostData: %@",post);
 
                let url:NSURL = NSURL(string: "https://dipinkrishna.com/jsonsignup.php")!
 
                let postData:NSData = post.dataUsingEncoding(NSASCIIStringEncoding)!
 
                let postLength:NSString = String( postData.length )
 
                let request:NSMutableURLRequest = NSMutableURLRequest(URL: url)
                request.HTTPMethod = "POST"
                request.HTTPBody = postData
                request.setValue(postLength as String, 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?
                do {
                    urlData = try NSURLConnection.sendSynchronousRequest(request, returningResponse:&response)
                } catch let error as NSError {
                    reponseError = error
                    urlData = nil
                }
 
                if ( urlData != nil ) {
                    let res = response as! NSHTTPURLResponse!;
 
                    NSLog("Response code: %ld", res.statusCode);
 
                    if (res.statusCode >= 200 && res.statusCode < 300)
                    {
                        let responseData:NSString  = NSString(data:urlData!, encoding:NSUTF8StringEncoding)!
 
                        NSLog("Response ==> %@", responseData);
 
                        //var error: NSError?
 
                        let jsonData:NSDictionary = try NSJSONSerialization.JSONObjectWithData(urlData!, options:NSJSONReadingOptions.MutableContainers ) 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"
                            }
                            let alertView:UIAlertView = UIAlertView()
                            alertView.title = "Sign Up Failed!"
                            alertView.message = error_msg as String
                            alertView.delegate = self
                            alertView.addButtonWithTitle("OK")
                            alertView.show()
 
                        }
 
                    } else {
                        let alertView:UIAlertView = UIAlertView()
                        alertView.title = "Sign Up Failed!"
                        alertView.message = "Connection Failed"
                        alertView.delegate = self
                        alertView.addButtonWithTitle("OK")
                        alertView.show()
                    }
                }  else {
                    let 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()
                }
            } catch {
                let alertView:UIAlertView = UIAlertView()
                alertView.title = "Sign Up Failed!"
                alertView.message = "Server Error!"
                alertView.delegate = self
                alertView.addButtonWithTitle("OK")
                alertView.show()
            }
        }   
    }

signinTapped in LoginVC.swift:

@IBAction func signinTapped(sender : UIButton) {
        let username:NSString = txtUsername.text!
        let password:NSString = txtPassword.text!
 
        if ( username.isEqualToString("") || password.isEqualToString("") ) {
 
            let alertView:UIAlertView = UIAlertView()
            alertView.title = "Sign in Failed!"
            alertView.message = "Please enter Username and Password"
            alertView.delegate = self
            alertView.addButtonWithTitle("OK")
            alertView.show()
        } else {
 
            do {
            let post:NSString = "username=\(username)&password=\(password)"
 
            NSLog("PostData: %@",post);
 
            let url:NSURL = NSURL(string:"https://dipinkrishna.com/jsonlogin2.php")!
 
            let postData:NSData = post.dataUsingEncoding(NSASCIIStringEncoding)!
 
            let postLength:NSString = String( postData.length )
 
            let request:NSMutableURLRequest = NSMutableURLRequest(URL: url)
            request.HTTPMethod = "POST"
            request.HTTPBody = postData
            request.setValue(postLength as String, 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?
            do {
                urlData = try NSURLConnection.sendSynchronousRequest(request, returningResponse:&response)
            } catch let error as NSError {
                reponseError = error
                urlData = nil
            }
 
            if ( urlData != nil ) {
                let res = response as! NSHTTPURLResponse!;
 
                NSLog("Response code: %ld", res.statusCode);
 
                if (res.statusCode >= 200 && res.statusCode < 300)
                {
                    let responseData:NSString  = NSString(data:urlData!, encoding:NSUTF8StringEncoding)!
 
                    NSLog("Response ==> %@", responseData);
 
                    //var error: NSError?
 
                    let jsonData:NSDictionary = try NSJSONSerialization.JSONObjectWithData(urlData!, options:NSJSONReadingOptions.MutableContainers ) as! NSDictionary
 
 
                    let success:NSInteger = jsonData.valueForKey("success") as! NSInteger
 
                    //[jsonData[@"success"] integerValue];
 
                    NSLog("Success: %ld", success);
 
                    if(success == 1)
                    {
                        NSLog("Login SUCCESS");
 
                        let 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"
                        }
                        let alertView:UIAlertView = UIAlertView()
                        alertView.title = "Sign in Failed!"
                        alertView.message = error_msg as String
                        alertView.delegate = self
                        alertView.addButtonWithTitle("OK")
                        alertView.show()
 
                    }
 
                } else {
                    let alertView:UIAlertView = UIAlertView()
                    alertView.title = "Sign in Failed!"
                    alertView.message = "Connection Failed"
                    alertView.delegate = self
                    alertView.addButtonWithTitle("OK")
                    alertView.show()
                }
            } else {
                let 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()
            }
            } catch {
                let alertView:UIAlertView = UIAlertView()
                alertView.title = "Sign in Failed!"
                alertView.message = "Server Error"
                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 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 โ†’

8 comments

  1. Hi Mansour,

    All the tutorials I have are pretty much outdated. My last tutorial was in 2015.
    I just got my blog back up a few days ago. I will be writing new tutorials soon.
    Sorry for the trouble.

    Thanks,
    Dipin

  2. dear

    i am try to learn IOS application i am using Xcode9.1 i try to follow this lesson but i have problem when i reach to LoginVC.swift i try to add new referencing outlet, i cannot i find this message “could not insert new outlet connection: could not find any information for the class named LoginVC”

    why this happens i am try to apply your tutorial step by step.

  3. When I run your code using my server , I get connection field with code = 500

    what might be the problem ?

  4. FInaly working tutorial!!!
    I managed to connect app with our rest API swift2 with little changes to what I need.

    Thank you so much!

  5. Hi,
    Great tutorial, well coded.
    Thanks you a lot you saved our lives ๐Ÿ˜‰

    Though, there is one more thing is missing which is ‘Forgot Password’.
    It will be great if you add this feature in your code.
    This will complete the App and I guess its essential.

    Regards

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.