Site icon Dipin Krishna

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.

  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

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.

Thanks, Hope it helps!

Exit mobile version