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?
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 🙁
Hi, I have updated the source code to be compatible with the latest version of Xcode.
Hi, I have updated the source code to be compatible with the latest version of Xcode.
Hi,
I have updated the source code to be compatible with the latest version of Xcode.
Hi Dipin,
Are you gonna update this tutorial to Xcode 6.3.1?
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?
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?
thanks for the tutorials
hey can you continue your series by adding more tutorials like user profile or something like that
thanks sir, it worked perfectly
can you continue your series by adding more tutorials like user profile or something like that
thanks
Can you check the swift code which posts the data.
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’;
I think you missed to add the “&” in between the post variables.
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.
Hi Hitesh,
Please check your php logs to find any issue related to the php code.
Thanks.
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
The internet connection is not able to resolve the url you specified.
Can you double check the url?
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?
Hey,
Can you make sure mysql is running?
If its running, can you verify in my.cnf that socket file is set to ‘/var/lib/mysql/mysql.sock’.
Please check the permissions also:
Thanks.
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).
And also, in the code, replace http://dipinkrishna.com with https://dipinkrishna.com.
This looks like a message from mysql.
Sorry for that, i had moved my website to a new server.
Please try now.
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
You can use NSUserDefaults to store the info, during login.
I already save the username in userdefaults.
Then later when they return, fill the login screen with the info from userdefaults.
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 !!!
Yes, you can do that.
https://www.dropbox.com/s/2x7vfxhl261xliq/Adding%20Swipe%20Gesture%20To%20View%20Controller.mov?dl=0
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?
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.
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.
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!
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.
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.
This is the response from your server:
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!
Thats, probably you are not getting data or the data returned is an invalid json string.
Can you double check what you are receiving?
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.
Try resetting the simulator. It might help.
https://www.dropbox.com/s/qb20th1si6kjd55/Screenshot%202015-01-07%2010.20.41.png?dl=0
You can always use my url for testing.
do I have to make a database with mysql and have a php file for this to work?
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.
You will have to rewrite it.
do i have to remove your code entirely?
or do i simply just change something like your URL?
Parse has its library and you can use it.
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?
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?
Dipin
Thanks a lot for this tutorial, I am just starting out (not in life, just in coding) and it is great.
Thanks again!
Yes, thats how i did it.
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
but there are not signup, how can i add that
https://dipinkrishna.com/blog/2013/12/ios-login-screen-tutorial-xcode-5-ios-7-storyboard-json
do you have this code objective c login Version?
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!
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 🙂
Cannot connect to mysql on the server side?
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
true great post , it reduced my API calling time.
Thanks a lot sir
The file is present in the archive attached to the post. Thanks.
Hello,
What is inside your file named ‘https://dipinkrishna.com/jsonsignup.php’ ?
Thanks
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.
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.
Thank you krishna . i will give a try 🙂 Great Job!
Yes.
Go to the storyboard.
Select the segue.
From the Attribute Inspector pane, Select the “Transition” you want.
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
How can i Have Flip animation between signin and signup
Use:
var url:NSURL = NSURL(string:”https://dipinkrishna.com/jsonlogin2.php”)!
and
var url:NSURL = NSURL.URLWithString(“https://dipinkrishna.com/jsonlogin2.php”)
in signinTapped
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
Please can you give more details on your solution, i am having the same problem
Thanks
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 ?
also, i tried to put “!” at the end of the line and noting
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
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.
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.
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
Hello,
Where did you add ! at the end? I’m having the same issue.
Thanks.
Great tutorial!
I fix it adding ! at the end.
Thank you, your tutorial really help me.
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.
Thanks dude, I’m from malaysia and doing FYP current year. It helps me a lot. New to iOS apps 🙂
Which line?
But Error was coming…”Expected Identifier in class declaration”
Plz give any solution
Thanks for posting these video
I’m looking forward to the next set of videos. Thanks for posting the source.
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.
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 🙂
Hey,
The source code has been updated.
Thanks.
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)
Hey,
Which line of code throws that error?
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
Zoom out and try to control drag.
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?
Sorry, i have updated the source to beta 6.
Do you have v.5 file with this project?
really nice, exactly what i need
Its now update for Xcode 6 beta 6. Thanks Ferran.
Hi!
It’s a great tutorial, but with the Xcode 6 beta 6 don’t works, a lot errors in the code.
Thanks!
Thanks. I have updated the source code. 🙂
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!
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!
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.
Hey, i will update the project for xcode 6 beta 5.
Getting error: “Type ‘NSString?’ does not conform to protocol ‘BooleanType.Protocol’ “