Tagged with:  

197 Responses to “iOS LOGIN Screen Tutorial with Server Authentication – JSON – PHP”

  1. Kamal says:

    Hey Dipin, great walkthrough! Informative and concise, just the way I like it. I was wondering if you could help me with something … I want this login view controller to be the initial view , however I must have my tab controller as the root view. How would I making the login screen initial and then pushing it into the tab bar controller. Please bear in mind, I am extremely new to objective C and iOS programming. Brand new computer science graduate , so I atleast know the basics :P

    • Hey,

      Its better to use “presentViewController” for the login screen.

      In your Appdelegate please set the tab bar controller as the root view controller.
      Then, use the following line in the viewDidLoad method of the main view of the tab controller.

      [self presentViewController:loginScreenVC animated:YES completion:nil];

      You can use

      [self dismissViewControllerAnimated:YES completion:nil];

      in the loginScreen view controller to return to the tab bar controller.

      Thanks.

  2. binita modi says:

    GNU gdb 6.3.50-20050815 (Apple version gdb-1708) (Mon Aug 8 20:32:45 UTC 2011)
    Copyright 2004 Free Software Foundation, Inc.
    GDB is free software, covered by the GNU General Public License, and you are
    welcome to change it and/or distribute copies of it under certain conditions.
    Type “show copying” to see the conditions.
    There is absolutely no warranty for GDB. Type “show warranty” for details.
    This GDB was configured as “x86_64-apple-darwin”.sharedlibrary apply-load-rules all
    Attaching to process 1474.
    2013-08-08 16:19:48.046 jsonLogin[1474:f803] PostData: username=Sunil Parmar&password=sunil123
    2013-08-08 16:19:48.079 jsonLogin[1474:f803] Response code: 0
    2013-08-08 16:19:48.081 jsonLogin[1474:f803] Error: Error Domain=NSURLErrorDomain Code=-1000 “bad URL” UserInfo=0x6eb06f0 {NSUnderlyingError=0x6eb03a0 “bad URL”, NSLocalizedDescription=bad URL}

    i write as per yr code … but stilll …. login fail is display….

    • You are having some issue with the url. Maybe it contains spaces. Plz check it.

      Also, try changing this line:

      NSString *post =[[NSString alloc] initWithFormat:@"username=%@&password=%@",[txtUsername text],[txtPassword text]];

      to:

      NSString *post =[[[NSString alloc] initWithFormat:@"username=%@&password=%@",[txtUsername text],[txtPassword text]] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  3. binita modi says:

    GNU gdb 6.3.50-20050815 (Apple version gdb-1708) (Mon Aug 8 20:32:45 UTC 2011)
    Copyright 2004 Free Software Foundation, Inc.
    GDB is free software, covered by the GNU General Public License, and you are
    welcome to change it and/or distribute copies of it under certain conditions.
    Type “show copying” to see the conditions.
    There is absolutely no warranty for GDB. Type “show warranty” for details.
    This GDB was configured as “x86_64-apple-darwin”.sharedlibrary apply-load-rules all
    Attaching to process 1065.
    2013-08-09 13:21:07.595 jsonLogin[1065:f803] PostData: user_name=Sunil%20Parmar&password=sunil123
    2013-08-09 13:21:07.603 jsonLogin[1065:f803] urldata is: (null)
    2013-08-09 13:21:07.604 jsonLogin[1065:f803] Response code: 0
    2013-08-09 13:21:07.605 jsonLogin[1065:f803] Error: Error Domain=NSURLErrorDomain Code=-1000 “bad URL” UserInfo=0xb59dd00 {NSUnderlyingError=0xb59d9b0 “bad URL”, NSLocalizedDescription=bad URL}
    (gdb)

    still this problm is coming… i try alot.. but not working… still give connection fail.. login fail

  4. Rohit says:

    Hi Dipin,
    Thanks for tutorial,I am very new in IOS.I have a query that i want if login is succesfully done then it will transfer to the new view control otherwise keep it in Login Screen.can you help me…

    • Use:

      HomeViewController *homeView = [[HomeViewController alloc] init];
      [self.navigationController pushViewController:homeView animated:YES];

      instead of the alertView when the login is success.

  5. Rohit says:

    Hello Sir,
    Thanks for this tutorial.I am very new in IOS and Objective C.
    I have one query that,I have created application with multiple screen,1st one is login screen,my query is that if successfully login is done then it transfer to new screen otherwise not.What to do plz help me as soon as possible.
    Thanks in advance

  6. Khai says:

    Hi, first I would to thanked u for this great tutorial. I’ve been following it step by step and I succeeded. However, just now I try to log in using the username “dipinkrishna” and password “password” but there is an error popup msg saying that the username/password is invalid. I’ve checked in the codes there’re no such message will be appear if the login failed. I wonder is the username and password have been change or something? many thanks in advance

  7. rahul says:

    Hello Sir,
    I have facing the problem with this line plz help me regarding ths . ths show a error
    how cn i resolve ths.
    plz send me mail regarding solution.
    // [NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[url host]];

    • Hi,
      If you are not using https, then you can remove that line.
      or add these lines to the top of the controller.

      @interface NSURLRequest (DummyInterface)
      + (BOOL)allowsAnyHTTPSCertificateForHost:(NSString*)host;
      + (void)setAllowsAnyHTTPSCertificate:(BOOL)allow forHost:(NSString*)host;
      @end
  8. Abrar says:

    hey man, awesome tutorial!

    I am trying it again now that I upgraded to xcode 5.0 and ios 7. and it seems to throw an exception and crash the program. Do you have any clue what it could be?

    • Abrar says:

      found the solution! . For some reason, I had an extra nil in the alertview after you successfully log in . Works after I removed it!

  9. Abrar says:

    scratch that. It doesn’t work. I think it has something to do with pressing ok on the alertview while already in another view. Any ideas? lol

    • Hey,

      I think, after successful login, you are showing an alertview and then moving to another viewcontroller.

      It would be better if you move the code for “Moving to second screen” to the click event of uialertview’s ok button.

      Lets assume that the current code is:

          HOMEViewController *homeView = [[HOMEViewController alloc] init];
          [self presentModalViewController:homeView animated:YES];
          [homeView release];
       
          UIAlertView *alertsuccess = [[UIAlertView alloc] initWithTitle:@"SUCCESS" message:@"Logged In Successfully" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
          [alertsuccess show];
          [alertsuccess release];

      Lets add a tag to the alertview, and then move the code to alertview’s ‘clickedButtonAtIndex’ event.

          UIAlertView *alertsuccess = [[UIAlertView alloc] initWithTitle:@"SUCCESS" message:@"Logged In Successfully" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
          alertsuccess.tag = 101;
          [alertsuccess show];
          [alertsuccess release];

      And add this:

      - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
      {
          if (alertView.tag == 101 && buttonIndex == 0)
          {
              HOMEViewController *homeView = [[HOMEViewController alloc] init];
              [self presentModalViewController:homeView animated:YES];
              [homeView release];
          }
      }
  10. safak says:

    thanks, nice tutorial

  11. alex says:

    great tut. Apple says that they will reject this setAllowsAnyHTTPSCertificate:forHost because it’s using a non-public API/s in the app. Would you know how to resolve this?

    thanks

  12. Sam says:

    Are there any plans to update this to iOS 7? JSON parsing is now a part of the framework no need for 3rd party libraries.

  13. Arch says:

    Thanks for this great tutorial.
    I ma new to iOS/JSON programming and need help here. I send my data to the restful servce url in this format {“username:”myuser”,”password”:”mypassword”} but I get an error -JSONRepresentation failed, not a valid type for JSON,
    Please help

    • Are you trying to send a json string to your api?

      • Arch says:

        yes, my backend application has published the restfult web service which I consume to interact with that app.

      • Can you copy/paste your block of code?

      • Arch says:

        ok that error got cleared but now I get response code 415
        my code looks like this:NSString *post =[[NSString alloc] initWithFormat:@”{\”username\”:\”%@\”,\”password\”:\”%@\”}”,[self.txtUserName text],[self.txtPaswd text]];

        NSURL *url=[NSURL URLWithString:@"http://112.23.82.110:9080/SSR/webapi/pager1/login"];

        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];

      • Seems to be a server side problem.

  14. kumar says:

    hi dipin , i really appreciate your work
    i have changed the parameters n also I’m providing right credentials but still it gives error “Login failed”.
    the response code is 200 and success=0
    what should be the problem?
    Plz guide me I’m new to iphone development
    thanks in advance.. :)

  15. kumar says:

    i didn’t get you??

  16. kumar says:

    Sorry about it
    Im logged in
    but I’m getting output in html format..
    what should i do??

  17. Raymond says:

    Hi, I’ve successfully launched your program, great work thanks.

    I would just like to know if how can I go to the next page after login in

    if(success == 1)
    {
    NSLog(@”Login SUCCESS”);
    [self alertStatus:@"Logged in Successfully." :@"Login Success!"];

    //enter code to next page here. (what code do I enter here)

    } else {

    thanks and regards

    • Use:

      HomeViewController *homeView = [[HomeViewController alloc] init];
      [self.navigationController pushViewController:homeView animated:YES];

      instead of the alertView when the login is success.

  18. narasimha says:

    how can i get source code for this project please tell me…

  19. jon says:

    Hi Dipin,
    Any idea when an Xcode 5/IOS 7 version will be available?
    Thanks
    Jon

  20. narasimha says:

    can u send me the same tutorial which is developed in xcode 5??It’ll be very helpful to me. Thanks in advance…

  21. Jai says:

    Sir, Its really help for me. Is the perfect tutorial for beginers. I need to know the code of the login page.

  22. jose says:

    Hi guys well structure tutotial. I am having a problem. When I put the original url NSURL *url=[NSURL URLWithString:@"http://dipinkrishna.com/jsonlogin.php"];
    the programs work perfectly. But when I put there my local addres it does not work I am putting http://localhost/jose/jsonlogin.php“. has anyone had the same proble any suggestions?. I tried restarting apache but it still not working. When i write in my browser localhost it shows “it works”.
    thanks

  23. Paul says:

    Great tutorial, How would I add a device id into this submission so I can store it for the purpose of push notifications?

  24. Paul says:

    Also how do I get the code to point to a UIWebView I have created if the login is a success?

    • Hi,

      If you want to go to another view/screen then use:

      HomeViewController *homeView = [[HomeViewController alloc] init];
      [self.navigationController pushViewController:homeView animated:YES];

      Or if you just want to show a uiwebview then use:

      UIWebView *webView = [[UIWebView alloc] initWithFrame:self.view.bounds]; 
      //Create a URL object.
      NSURL *url = [NSURL URLWithString:@"http://dipinkrishna.com"];
      //URL Requst Object
      NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
      //Load the request in the UIWebView.
      [webView loadRequest:requestObj];
      //show the webview
      [self.view addSubview:webView];
      • Paul says:

        Scratch that last question I manage to figure it out, I used the second method you gave me. just one more question, my app is sitting over the navigation bar, is there any way I can set the size of the uiwebview or just get it to nudge down a little so its not under the clock? Thanks for all your help!

      • This is a quick fix:

        webView.frame = CGRectMake(webView.frame.origin.x, webView.frame.origin.y + 20, webView.frame.size.width, webView.frame.size.height);
        UIWebView *webView = [[UIWebView alloc] initWithFrame:self.view.bounds];
        //Change Frame
        webView.frame = CGRectMake(webView.frame.origin.x, webView.frame.origin.y + 20, webView.frame.size.width, webView.frame.size.height);
        //Create a URL object.
        NSURL *url = [NSURL URLWithString:@"http://dipinkrishna.com"];
        //URL Requst Object
        NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
        //Load the request in the UIWebView.
        [webView loadRequest:requestObj];
        //show the webview
        [self.view addSubview:webView];
      • Paul says:

        Thanks that works like a charm, just one more.

        Is their any way to pass the post data used to verify the username and pass into the web view?

      • Use [txtUsername text] and [txtPassword text]

        eg:

        NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://dipinkrishna.com?username=%@&password=%@", [txtUsername text],[txtPassword text]]];
      • If you are planning to ‘POST’ the data to the web view, see the below example:

        NSURL *url = [NSURL URLWithString: @"http://dipinkrishna.com/jsonlogin.php"];
        NSString *postData =[[NSString alloc] initWithFormat:@"username=%@&password=%@",[txtUsername text],[txtPassword text]];
         
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL: url];
        [request setHTTPMethod: @"POST"];
        [request setHTTPBody: [postData dataUsingEncoding: NSUTF8StringEncoding]];
         
        [webView loadRequest: request];
      • Paul says:

        Yes that is what im trying to do. Ime using this but doesn’t seem to be passing any data through

        UIWebView *webView = [[UIWebView alloc] initWithFrame:self.view.bounds];
        //Change Frame
        webView.frame = CGRectMake(webView.frame.origin.x, webView.frame.origin.y + 20, webView.frame.size.width, webView.frame.size.height);
        //Create a URL object.
        NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://www.mysite.co.uk/testpost.php?username=%@&password=%@", [_txtUsername text],[_txtPassword text]]];
        //URL Requst Object
        NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
        //Load the request in the UIWebView.
        [webView loadRequest:requestObj];
        //show the webview
        [self.view addSubview:webView];

        The contents of the testpost.php is

      • try using the ‘POST’ version.

        NSURL *url = [NSURL URLWithString: @"http://dipinkrishna.com/jsonlogin.php"];
        NSString *postData =[[NSString alloc] initWithFormat:@"username=%@&password=%@",[txtUsername text],[txtPassword text]];
         
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL: url];
        [request setHTTPMethod: @"POST"];
        [request setHTTPBody: [postData dataUsingEncoding: NSUTF8StringEncoding]];
         
        [webView loadRequest: request];
  25. Paul says:

    ahhh I need to stop using php tags :)

    print_r($_POST);

      • Paul says:

        Basically what I am trying to achieve is when your login script gives a success and I send it into a webview, I am trying to get the same information (username and password from the text inputs) into the webview also. Is their any way to do this?

      • This should do:

        NSURL *url = [NSURL URLWithString: @"http://www.mysite.co.uk/testpost.php"];
        NSString *postData =[[NSString alloc] initWithFormat:@"username=%@&password=%@",[_txtUsername text],[_txtPassword text]];
        // Create the request object
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL: url];
        [request setHTTPMethod: @"POST"];
        [request setHTTPBody: [postData dataUsingEncoding: NSUTF8StringEncoding]];
         
        // create the web view
        UIWebView *webView = [[UIWebView alloc] initWithFrame:self.view.bounds];
        //Change Frame
        webView.frame = CGRectMake(webView.frame.origin.x, webView.frame.origin.y + 20, webView.frame.size.width, webView.frame.size.height);
         
        // Load the request
        [webView loadRequest: request];
         
        //show the webview
        [self.view addSubview:webView];
      • Paul says:

        Brilliant, works great. Thanks!

  26. sulaf says:

    Hello,

    thank you for this informative tutorial , I had one problem after adding the json code, when I ran the code and i was reading the console message, i noticed it was always taking username value as null , so I deleted the field and added it again and then it displayed the username correctly in the console, but when i did that the server in which i’m uploading the php code at got a 500 error, I deleted that php code and added it again and still facing the same error code.

    can you help?
    thank you!

Leave a Reply

*


Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Visit our friends!

A few highly recommended friends...

Unlimited Domain Hosting Unlimited Domain Hosting
IP Address : 107.21.163.227
Country : United States
Featured FREE Resource: