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.
- 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 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!
Xcode Project : SwiftLoginScreen.zip
Php Code : SwiftJsonLoginPHP.zip
Hi
Thanks for the lesson, can I access the source code?
Many thanks for this excellent tutorial.
From the app?
Hello Dipin,
I can not login on our site wordpress also PHP.
Please help,
Thanks,
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?
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.
Hi Dipin,
Many thanks for this excellent tutorial.
Is it possible to update it for Xcode version 7.3.1?
thank you
Thanks a lot your post help me very much, i am recently switch to iOS from dot net.
Can you make sure you have data returned?
if(urlData != nil) {
….
}
Hi Dipin! I have the same problem that James, my xcode version is 7 beta.
Nice tutorial
Thanks.
Check if the value exist:
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
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:
Hope it helps!
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…
What’s your xcode version?
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”
Sorry. Try now.
I had added new fields to the php script on my server for another tutorial.
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?
Hey,
Whats the url you are trying to use?
Try 127.0.0.1 instead of localhost.
Thanks.
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
Thanks a lot man and keep up a good work!
Can you check your php logs and figure out what the error is?
How can I fix this?
Hi,
The php script is not perfect.
The error “username already exists” can be due to some other mysql related error.
Thanks.
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!
Hi,
I have updated the download list with a link to the source for xcode 7 beta.
I got a lot of errors, I am at XCODE 7 beta,
Could you fix it ?
Thanks!
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.
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
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!
It looks like your username/password is incorrect.
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
In this tutorial, it does take you to the “Home” screen after successful login.
Hi,
The username might already exist of the DB.
Or it can be some other error, you can better the php script to catch them.
Thanks.
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
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.
Thank you so much for fixing the errors in the latest version. It helped me out sooooooooo much! Thank you again!
Can you make sure you are using the latest source code?