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.
- Create a New project. And add the Screens and Segues/transitions.
- Home – Check for an existing session, else goto Login
- Login Screen – Post data to URL and parse the JSON response.
- Signup Screen – Post data to URL and parse the JSON response.
- 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? 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