For Swift tutorial, See: Swift + XCode 6 + iOS 8 + JSON
iOS Login Screen tutorial : XCode 5 + ios 7 + Storyboard + JSON
This tutorial will guide you to create a simple app with a Login screen which takes username and password from the user and then posts it to an url and parses the JSON response.
- Create a New project.
- Create the Screens and the Segue/transition.
- Declare and Connect the properties and actions to the UI elements.
- Set actions for Background Click and text field Return events.
- Post data to URL and parse the JSON response.
1. Create a New project.
- Launch XCode.
- Click: File->New Project… and choose: Single View Application
- Name your project, here i am using ‘LoginScreenTutorial’
When you choose Single View Application, XCode creates many files for you, among which the following files are of our interest:
ViewController.h
ViewController.m
Main.storyboard
Next: Create the Screens and the Segue/transition
- Create a New project.
- Create the Screens and the Segue/transition.
- Declare and Connect the properties and actions to the UI elements.
- Set actions for Background Click and text field Return events.
- Post data to URL and parse the JSON response.
2. Create the Screens and the Segue/transition.
- Add the labels, text fields and button to the Login Screen.
Go to the ‘Main.storyboard’. It will have a View Controller by default. Lets make it our Login Screen. Add the required labels, text fields and a button. - Add a new ‘View Controller’ for the home page.
We will add a new View Controller to the storyboard for the Home Screen. - Create a segue from Login Screen to Home Screen.
Let’s create a Segue from our Login Screen to the Home Screen.
We will use that to go to the Home screen when Login is success.
Next: Declare and Connect the properties and actions to the UI elements
- Create a New project.
- Create the Screens and the Segue/transition.
- Declare and Connect the properties and actions to the UI elements.
- Set actions for Background Click and text field Return events.
- Post data to URL and parse the JSON response.
3. Declare and Connect the properties and actions to the UI elements.
In Login Screen View Controller, we will add the properties to access the username and password field and add an action to the Sigin in button.
Next: Set actions for Background Click and text field Return events
- Create a New project.
- Create the Screens and the Segue/transition.
- Declare and Connect the properties and actions to the UI elements.
- Set actions for Background Click and text field Return events.
- Post data to URL and parse the JSON response.
4. Set actions for Background Click and text field Return events.
Try running the project in the simulator. You can see that when we select a textfield the keypad pops up. And there is no way we can make the keyboard disappear, so that we can click the sign in button.
So, what we are going to do here is to make the keypad disappear when we click on the ‘return’ button on the keypad or tap somewhere on the background of the view.
Next: Post data to URL and parse the JSON response
- Create a New project.
- Create the Screens and the Segue/transition.
- Declare and Connect the properties and actions to the UI elements.
- Set actions for Background Click and text field Return events.
- Post data to URL and parse the JSON response.
5. Post data to URL and parse the JSON response.
Here, i am going to POST the username and password to an url and then parse its JSON response.
Add the following code to signinClicked()
- (IBAction)signinClicked:(id)sender { NSInteger success = 0; @try { if([[self.txtUsername text] isEqualToString:@""] || [[self.txtPassword text] isEqualToString:@""] ) { [self alertStatus:@"Please enter Email and Password" :@"Sign in Failed!" :0]; } else { NSString *post =[[NSString alloc] initWithFormat:@"username=%@&password=%@",[self.txtUsername text],[self.txtPassword text]]; NSLog(@"PostData: %@",post); NSURL *url=[NSURL URLWithString:@"https://dipinkrishna.com/jsonlogin.php"]; NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[postData length]]; NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; [request setURL:url]; [request setHTTPMethod:@"POST"]; [request setValue:postLength forHTTPHeaderField:@"Content-Length"]; [request setValue:@"application/json" forHTTPHeaderField:@"Accept"]; [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; [request setHTTPBody:postData]; //[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[url host]]; NSError *error = [[NSError alloc] init]; NSHTTPURLResponse *response = nil; NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; NSLog(@"Response code: %ld", (long)[response statusCode]); if ([response statusCode] >= 200 && [response statusCode] < 300) { NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding]; NSLog(@"Response ==> %@", responseData); NSError *error = nil; NSDictionary *jsonData = [NSJSONSerialization JSONObjectWithData:urlData options:NSJSONReadingMutableContainers error:&error]; success = [jsonData[@"success"] integerValue]; NSLog(@"Success: %ld",(long)success); if(success == 1) { NSLog(@"Login SUCCESS"); } else { NSString *error_msg = (NSString *) jsonData[@"error_message"]; [self alertStatus:error_msg :@"Sign in Failed!" :0]; } } else { //if (error) NSLog(@"Error: %@", error); [self alertStatus:@"Connection Failed" :@"Sign in Failed!" :0]; } } } @catch (NSException * e) { NSLog(@"Exception: %@", e); [self alertStatus:@"Sign in Failed." :@"Error!" :0]; } if (success) { [self performSegueWithIdentifier:@"login_success" sender:self]; } } - (void) alertStatus:(NSString *)msg :(NSString *)title :(int) tag { UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title message:msg delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil]; alertView.tag = tag; [alertView show]; }
On success, we bring up the Home screen using this line of code:
[self performSegueWithIdentifier:@"login_success" sender:self];
My php code at dipinkrishna.com/jsonlogin.php
<?php header('Content-type: application/json'); if($_POST) { if($_POST['username'] == 'dipinkrishna' && $_POST['password'] == 'password') { echo '{"success":1}'; } else { echo '{"success":0,"error_message":"Username and/or password is invalid."}'; } }else { echo '{"success":0,"error_message":"Username and/or password is invalid."}';} ?>
Now, try running the project in the simulator.
Now, If you add views and controls to your home screen and need to access those, you need to attach a class to that home screen.
See:
Download the full source code using the link below:
Xcode Project : Json Login App