Site icon Dipin Krishna

iOS LOGIN Screen Tutorial with Server Authentication – JSON – PHP

 This tutorial will guide you to create a simple app with a Login screen which takes username and password from the user and then POST it to an url and parse the JSON response.

  1. Create a New project.
  2. Create the Screen(View).
  3. Declare and Connect the properties and functions to the UI elements.
  4. Set actions for Background Click and text field Return events.
  5. Post data to URL and parse the JSON response.

1. Create a New project.


1. Launch XCode .
2. Click: File->New Project…
and choose: Single View Application

3. Name the project: ‘LoginJson’ and you can give a file prefix also, here i have given “DK”.

When you choose Single View Application, XCode creates many files for you, among which the following files are of our interest:
Classes\DKViewControl.h
Classes\DKViewControl.m
Resources\DKViewControl.xib
the DKViewControl.xib is the design of the view
the other files are used for the class files for the view
and also XCode creates the view and puts it as the main screen when the program launches.

Next: Create the Loign Screen(View)

  1. Create a New project.
  2. Create the Screen(View).
  3. Declare and Connect the properties and functions to the UI elements.
  4. Set actions for Background Click and text field Return events.
  5. Post data to URL and parse the JSON response.

2. Create the Screen(View)


1. Select the xib file(DKViewController_iPhone.xib) from the navigation tree.
2. Drag and drop labels, test fields and round rect button to create the login screen. See the video:

Set the password field as secure.

Next: Declare and Connect the properties and functions to the UI elements

  1. Create a New project.
  2. Create the Screen(View).
  3. Declare and Connect the properties and functions to the UI elements.
  4. Set actions for Background Click and text field Return events.
  5. Post data to URL and parse the JSON response.

3. Declare and Connect the properties and functions to the UI elements


1. Click on the Assistant Editor.
2. Right click on the text fields and bind the properties for it.
3. Right click on the login button and bind a action to it.

Next: Set actions for Background Click and text field Return events.

  1. Create a New project.
  2. Create the Screen(View).
  3. Declare and Connect the properties and functions to the UI elements.
  4. Set actions for Background Click and text field Return events.
  5. Post data to URL and parse the JSON response.

4. Set Actions for Background Click and text field Return events.

We need to batch the events such as the background clicks(user taps in the empty area of the view) and when the return key in pressed in the textfields.

What i am doing here is:

  1. Create the action backgroundClick().
  2. Change the class of the view from UIView to UIControl
  3. Attach the action to the Touchup Inside event of the UIControl.
  4. Attach the action to the  Did End On Exit event of both the text field.



 

Next: Post data to URL and parse the JSON response.

 

  1. Create a New project.
  2. Create the Screen(View).
  3. Declare and Connect the properties and functions to the UI elements.
  4. Set actions for Background Click and text field Return events.
  5. Post data to URL and parse the JSON response.


5. Post data to URL and parse the JSON response.

    1. Lets get the Json framework and add it to the project.

       

    2. Now, Lets POST data to an url when the login button is clicked.
      • Import the json header file to the login screen view controller.
        Open DKViewController.madd the following line to the header section.
        #import "SBJson.h"
      • Lets write a small function to show alert messages.
        Add the following code just above the line “- (IBAction)loginClicked:(id)sender {“:
        - (void) alertStatus:(NSString *)msg :(NSString *)title
        {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title
                                                                message:msg
                                                               delegate:self
                                                      cancelButtonTitle:@"Ok"
                                                      otherButtonTitles:nil, nil];
         
            [alertView show];
        }
      • Add the following code to loginClicked()
        - (IBAction)loginClicked:(id)sender {
            @try {
         
                if([[txtUsername text] isEqualToString:@""] || [[txtPassword text] isEqualToString:@""] ) {
                    [self alertStatus:@"Please enter both Username and Password" :@"Login Failed!"];
                } else {
                    NSString *post =[[NSString alloc] initWithFormat:@"username=%@&password=%@",[txtUsername text],[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:@"%d", [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: %d", [response statusCode]);
                    if ([response statusCode] >=200 && [response statusCode] <300)
                    {
                        NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
                        NSLog(@"Response ==> %@", responseData);                    
         
                        SBJsonParser *jsonParser = [SBJsonParser new];
                        NSDictionary *jsonData = (NSDictionary *) [jsonParser objectWithString:responseData error:nil];
                        NSLog(@"%@",jsonData);
                        NSInteger success = [(NSNumber *) [jsonData objectForKey:@"success"] integerValue];
                        NSLog(@"%d",success);
                        if(success == 1)
                        {
                            NSLog(@"Login SUCCESS");
                            [self alertStatus:@"Logged in Successfully." :@"Login Success!"];
         
                        } else {
         
                            NSString *error_msg = (NSString *) [jsonData objectForKey:@"error_message"];
                            [self alertStatus:error_msg :@"Login Failed!"];
                        }
         
                    } else {
                        if (error) NSLog(@"Error: %@", error);
                        [self alertStatus:@"Connection Failed" :@"Login Failed!"];
                    }
                }
            }
            @catch (NSException * e) {
                NSLog(@"Exception: %@", e);
                [self alertStatus:@"Login Failed." :@"Login Failed!"];
            }
        }

       
      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."}';}
      ?>
    3. Now, run the application in the simulator. Don’t forget to change the url to your’s.

 

Download the full source code using the below link:

Hope it helps………..

Exit mobile version