Skip to content

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 posts it to a url and parses the JSON response form the server.

  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:

Link: Json Login App

Hope it helps………..

Pages: 1 2 3 4 5

Dipin Krishna

Written by Dipin Krishna

Senior full-stack engineer — 15 years across Django, Laravel, SwiftUI and the infrastructure underneath. Available for contract work.

Work with me →

218 comments

  1. Hello Sir,

    I have ran code and its given me following error pelase let me know what i have to do for it,

    Error: Error Domain=NSURLErrorDomain Code=-1005 “The network connection was lost.” UserInfo=0x8da2030.

    Thanks,

  2. hi Dipin, my logintodb.php is below:

    $host = “localhost”;
    $user = “root”;
    $pass = “root”;
    $db=”iwll”;

    $r = mysql_connect($host, $user, $pass);

    if (!$r) {
    echo “Could not connect to server\n”;
    trigger_error(mysql_error(), E_USER_ERROR);
    } else {
    echo “Connection established\n”;
    }

    echo mysql_get_server_info() . “\n”;
    $r2 = mysql_select_db($db);

    if (!$r2) {
    echo “Cannot select database\n”;
    trigger_error(mysql_error(), E_USER_ERROR);
    } else {
    echo “database selected\n”;
    }
    $us=$_POST[‘username’];
    $pw=$_POST[‘password’];
    $result=mysql_query(“select username,pass from login where username=’$us’ and pass=’$pw'”);

    $row=mysql_fetch_array($result);
    if($row[“username”]==$us && $row[“pass”]==$pw)
    {
    echo ‘{“success”:1}’;

    }
    else
    {
    echo ‘{“success”:0,”error_message”:”Username and/or password is invalid.”}’;

    }

  3. if i changed like that my output is:
    2014-11-05 16:24:06.764 logintodb[90940:90b] Response ==> Connection established
    5.5.38
    database selected
    {“success”:1}
    2014-11-05 16:24:06.764 logintodb[90940:90b] Success: 0
    and i got pop-up as Login failed
    why i got initially success:1 and then success:0
    pls explain me?

  4. nice tutorial.i have written my php code as:
    if($row[“username”]==$u && $row[“pass”]==$pw)
    {
    echo ‘”success”:1’;
    }
    else
    {
    echo ‘{“success”:0,”error_message”:”Username and/or password is invalid.”}’;

    }
    but i got in console pane as:2014-11-04 12:06:14.701 logintodb[5003:90b] Response ==> Connection established
    5.5.38
    database selected
    “success”:1
    2014-11-04 12:06:14.701 logintodb[5003:90b] Success: 0
    i dont know what it means?pls help me?

  5. Excellent tutorial! I have tried with this code.i am using MAMP server.so i don’t know what i have to put here:
    NSURL *url=[NSURL URLWithString:@”https://dipinkrishna.com/jsonlogin.php”];
    could u pls help me?

  6. What do you mean by setting tab bar controller as the root view controller. Does it mean selecting this as a initial view controller? Are they same concept? How do you set a view controller as a root view controller? Could you provide sample code, please?

  7. hi dipin,
    thanx for your wonderful tutorial.It works for me.
    but there is one problem, when i tried to change my php file code to get username and password from mysql database i got an error saying signin failed. will u pls send me a php code where mysql database connectivity is done and in that case if there is any change i would like to do in my objective C code to get response from edited php file becoz right now i am getting a response(NULL) and success:0.
    thanks in advance.

  8. When i run this code, show username password is invalid.And show json data is null.why?

  9. Hey,

    If you are saving the login info and status in user defaults, then clear them and send the user to the login page.

    [[NSUserDefaults standardUserDefaults] setPersistentDomain:[NSDictionary dictionary] forName:[[NSBundle mainBundle] bundleIdentifier]];
    [[NSUserDefaults standardUserDefaults] synchronize];

    If your website/server uses cookies, you may even clear that too.
    Example:

    for(NSHTTPCookie *cookie in [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies])
     {
       if([[cookie domain] rangeOfString:@"dipinkrishna.com"].location != NSNotFound)
       {
         [[NSHTTPCookieStorage sharedHTTPCookieStorage] deleteCookie:cookie];
       }
     }
  10. Hello bro,

    Thank you for this tutorial, i have a follow up question.. how will i end logging out the application? thank u so much

  11. 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!

  12. 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];
  13. 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?

  14. try using the ‘POST’ version.

    NSURL *url = [NSURL URLWithString: @"https://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];
  15. 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

  16. If you are planning to ‘POST’ the data to the web view, see the below example:

    NSURL *url = [NSURL URLWithString: @"https://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];
  17. Use [txtUsername text] and [txtPassword text]

    eg:

    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"https://dipinkrishna.com?username=%@&password=%@", [txtUsername text],[txtPassword text]]];
  18. 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?

  19. 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:@"https://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];
  20. 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!

  21. 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:@"https://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];
  22. Great tutorial, How would I add a device id into this submission so I can store it for the purpose of push notifications?

  23. Thank you sir, for this tutorial
    this tutorial is provide good platform for bigeners.

    thanks allot…..

  24. in adittion I am receiving this messages in console
    2014-01-14 17:11:46.829 LoginJSon[1067:a0b] Response ==>
    2014-01-14 17:11:46.830 LoginJSon[1067:a0b] (null)
    2014-01-14 17:11:46.830 LoginJSon[1067:a0b] 0

  25. Hi guys well structure tutotial. I am having a problem. When I put the original url NSURL *url=[NSURL URLWithString:@”https://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

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

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

  28. Use:

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

    instead of the alertView when the login is success.

  29. 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

  30. 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.. 🙂

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

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

  33. 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

  34. 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.

  35. 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

  36. 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];
        }
    }
  37. 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

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

  39. 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?

  40. 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
  41. 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]];

  42. 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

  43. 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

  44. Use:

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

    instead of the alertView when the login is success.

  45. 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…

  46. 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

  47. 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.

  48. 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];
  49. 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….

  50. 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 😛

  51. Hi,

    When you get a success, replace the alert with the following code.

    NSString *postHTML = [[NSString alloc] initWithFormat: @"<html><body></body> \
                          <script>var form = document.createElement('form'); \
                          input = document.createElement('input'); \
                          form.action = 'https://dipinkrishna.com/jsonlogin.php'; \
                          form.method = 'post'; \
                          var usernameField = document.createElement('input'); \
                          usernameField.setAttribute('type', 'hidden'); \
                          usernameField.setAttribute('name', 'username'); \
                          usernameField.setAttribute('value', '%@'); \
                          form.appendChild(usernameField); \
                          var passwordField = document.createElement('input'); \
                          passwordField.setAttribute('type', 'hidden'); \
                          passwordField.setAttribute('name', 'password'); \
                          passwordField.setAttribute('value', '%@'); \
                          form.appendChild(passwordField); \
                          document.body.appendChild(form); \
                          form.submit();</script> \
                          </html>", [txtUsername text], [txtPassword text] ];
     
    UIWebView *webview = [[UIWebView alloc]initWithFrame:CGRectMake(0, 0, 320,460)];
    [webview loadHTMLString:postHTML baseURL:nil];
    [self.view addSubview:webview];

    This creates and loads a UIWebView with html.
    The html content has the JS code to post data to an url.
    Please adjust the url and the name fields.
    Thanks!

  52. Dipin, like everyone else said, this tutorial is the best I’ve seen out there. I’m trying to tailor what you’ve posted to a URL in an iOS login page. The URL is https://quantdesk.lucenaresearch.com/#login. I changed the login field and added the required line for an https url.

    My result is that I get
    2013-07-08 15:17:29.762 LoginJson[51681:c07] PostData: [email protected]&password=xxxxxxxxx
    2013-07-08 15:17:30.068 LoginJson[51681:c07] Response code: 405
    (lldb)

    It seems like the method is not accepted. Do you have any idea how to resolve this issue?

    In the developer console when I login with my credentials on the actual web browser, the response is as follows

    Request URL:https://quantdesk.lucenaresearch.com/lr/api/token
    Request Method:POST
    Status Code:200 OK
    Request Headersview source
    Accept:application/json, text/javascript, */*; q=0.01
    Accept-Encoding:gzip,deflate,sdch
    Accept-Language:en-US,en;q=0.8
    Connection:keep-alive
    Content-Length:56
    Content-Type:application/json
    Cookie:__utma=216204950.464340013.1373310569.1373310569.1373310569.1; __utmb=216204950.1.9.1373311137524; __utmc=216204950; __utmz=216204950.1373310569.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)
    Host:quantdesk.lucenaresearch.com
    Origin:https://quantdesk.lucenaresearch.com
    Referer:https://quantdesk.lucenaresearch.com/
    User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.93 Safari/537.36
    X-Requested-With:XMLHttpRequest
    Request Payload
    {user:xxxxxxx, pass:xxxxxxxxx}
    pass: xxxxxxxxx
    user: xxxxxxxxx
    Response Headers
    Access-Control-Allow-Credentials:true
    Access-Control-Allow-Headers:Keep-Alive,Authorization,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type
    Access-Control-Allow-Methods:GET, POST, PUT, DELETE, OPTIONS
    Access-Control-Allow-Origin:https://quantdesk.lucenaresearch.com
    Connection:keep-alive
    Content-Encoding:gzip
    Content-Type:application/json;charset=UTF-8
    Date:Mon, 08 Jul 2013 19:18:57 GMT
    Server:nginx
    Transfer-Encoding:chunked
    Vary:Accept-Encoding

  53. heyyy..
    i m getting response data in xml…
    how can i display it in my app?
    please reply me asap…

  54. I run program and it have response result:
    2013-07-02 16:52:17.708 avl[5734:12e03] PostData: UserName=qazvin133&Password=qazvin133
    2013-07-02 16:52:22.825 avl[5734:12e03] Response code: 200
    2013-07-02 16:52:22.826 avl[5734:12e03] Response ==>
    2013-07-02 16:52:23.322 avl[5734:12e03] (null)
    2013-07-02 16:52:23.322 avl[5734:12e03] 0

  55. Nevermind again, I figured it out!

    NSString *retUser =(NSString *)[jsonData objectForKey:@”user”];

    Thank you!

  56. Oh, I actually figured that part out by adding all json “m” to the Build Phases, Compile Sources.

    I do have another question for you however. The way you wrote your php you return a 0 or 1. In mine, I actually look to return a String. how would I rewrite this part of the objC code to return a string versus the int?

    NSDictionary *jsonData = (NSDictionary *) [jsonParser objectWithString:responseData error:nil];
    NSLog(@”%@”,jsonData);
    NSInteger success = [(NSNumber *) [jsonData objectForKey:@”success”] integerValue];
    NSLog(@”%d”,success);

  57. Yep, you were right it fixed that error. But now I get a new one:

    Undefined symbols for architecture i386:
    “_OBJC_CLASS_$_SBJsonParser”, referenced from:
    objc-class-ref in Login.o
    ld: symbol(s) not found for architecture i386
    clang: error: linker command failed with exit code 1 (use -v to see invocation)

    Any thoughts on why I would see this? Thank you so much.

  58. Great tutorial, everything works except I receive an error on this line:

    NSDictionary *jsonData = (NSDictionary *) [jsonParser objectWithString:responseData:nil];

    The error: no visible @interface for SBJsonParser declares the selecter ‘objectWithString:error’

    I’m in to modify the JSON framework, change imports, or tweak code? Thank you.

  59. Hi,

    The Json parsing section in my code, looks for a format
    {“success”:1, error_message: “message”}
    Your’s might be something different. Please check and change the code accordingly.

  60. grt tutorial…
    my problem is i m getting this error:
    Response code: 200
    Object reference not set to an instance of an object.

  61. first of all, this is a great tutorial. my problem is how can i set when login successfully the program will jump to next view and only when the login failed the alter will comes out..
    thanks Dipin

  62. This was a very difficult debug on my side. I didn’t think about mod_rewrite which is because my website converts any urls without www to have www. When it does this, the POST data is lost. So adding www fixed it for me. I imagine redirecting urls and other things would give a similar issue.

  63. how i get the actual location of user..not of the device which are fixed in xcode debug arrow..please reply me asp.

  64. – (IBAction)Signin:(id)sender {

    @try {

    if([[username text] isEqualToString:@””] || [[password text] isEqualToString:@””] ) {
    [self alertStatus:@”Please enter both Username and Password” :@”Login Failed!”];
    } else {
    NSString *post =[[NSString alloc] initWithFormat:@”userName=%@&password=%@”,[username text],[password text]];
    NSLog(@”PostData: %@”,post);

    NSURL *url=[NSURL URLWithString:@”http://cgi.soic.indiana.edu/~team34/login.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] %@”, 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!”];
    }
    }

    – (IBAction)backgroundClick:(id)sender {
    [password resignFirstResponder];
    [username resignFirstResponder];
    }

  65. I am having issues with trying to connect the login to my mysql server. I keep getting this in the output in Xcode : 2013-04-23 20:25:46.990 FriendsOnTap[68927:f803] PostData: userName=k&password=k
    2013-04-23 20:25:47.149 FriendsOnTap[68927:f803] Response code: 200
    2013-04-23 20:25:47.150 FriendsOnTap[68927:f803] Response ==> 1
    2013-04-23 20:25:47.150 FriendsOnTap[68927:f803] (null)
    2013-04-23 20:25:47.150 FriendsOnTap[68927:f803] 0
    Then it says login failed and it pushes to the next to view anyways.

  66. This is great !!

    Appreciate your effort . I could run the application and test the code . Thank you Dipin .

  67. it worked for me when i changed header.But please let me know if I cab add more views to this project and how to do that?I dont have a Navigation Control.Do I need to add that?

  68. Your server side doesn’t matter as long as the app gets a proper json response from it.
    Please post your json string here. I will give you the code to parse it.

  69. Hi,
    Please let me know how to make this work fo my login app which has a rails back ground.This doesnt work for me.In android app I am creating a json Object named user and username and password are inside user.

  70. hey! thank you for this great tutorial 🙂
    plz if you have a similar tutorial for a registration form ( when i click on submit button , data must be stored in database) can you give me code i write in .m file
    thank you

  71. @try {

    if([[emailTextfield text] isEqualToString:@””] || [[passwordTextfield text] isEqualToString:@””] ) {
    [self alertStatus:@”Please enter both Username and Password” :@”Login Failed!”];
    } else {
    NSString *loginTag = @”login”;
    NSString *post =[[NSString alloc] initWithFormat:@”tag=%@&email=%@&password=%@”,loginTag,[emailTextfield text],[passwordTextfield text]];
    NSLog(@”PostData: %@”,post);

    NSURL *url=[NSURL URLWithString:@”http://www.businessreputationalert.com/android_apps/”];

    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] %@”, 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!”];
    }

    i have changed the code like this.
    but the problem is in parsing the data. NSLog(@”=============>>>>%@”,jsonData); this line return me a null value. can you tell me how to fixed that?

  72. This is a great tutorial for all the beginners like me but only problem is i am using a different url. and although i am giving a correct username and password it is showing me a msg field “login failed”.

    debugger says me..

    Response ==> {“tag”:”login”,”success”:1,”error”:0,”uid”:”76″,”user”:{“email”:”[email protected]”},”profile”:[{“profile_id”:”84″,”profile_name”:”Toyota Of Manhattan”},{“profile_id”:”82″,”profile_name”:”Mercedes-Benz of Nanuet”}…………..
    ……410670288&v=wall”,”date”:”13\/10\/12″,”profile_id”:”79″}]}

    2013-03-21 16:58:07.663 Buisness Reputation[1984:c07] =============>>>>(null)
    2013-03-21 16:58:07.663 Buisness Reputation[1984:c07] 0

  73. – (IBAction)LOGIN:(id)sender {

    @try {

    if([[_Name text] isEqualToString:@””] || [[_Passwort text] isEqualToString:@””] ) {

    } else {
    NSString *post =[[NSString alloc] initWithFormat:@”email=%@&password=%@”,[_Name text],[_Passwort text]];
    NSLog(@”PostData: %@”,post);

    NSURL *url=[NSURL URLWithString:@”http://www.myURL.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];

    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] %@”, 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”);

    UIAlertView *PopUp = [[UIAlertView alloc]
    initWithTitle:@”Logged in (y)”
    message:@”Welcome”
    delegate:nil
    cancelButtonTitle:@”Ok”
    otherButtonTitles:nil];
    [PopUp show];

    } else {

    NSString *error_msg = (NSString *) [jsonData objectForKey:@”error_message”];

    }

    } else {
    if (error) NSLog(@”Error: %@”, error);

    }
    }
    }
    @catch (NSException * e) {
    NSLog(@”Exception: %@”, e);

    }

    }

    @end

  74. Ok i checked my URL and it was wrong -.-
    But there’s now another mistake:
    2013-03-13 15:01:51.689 Test[2434:c07] PostData: [email protected]&password=test
    2013-03-13 15:01:51.828 Test[2434:c07] Response code: 200
    2013-03-13 15:01:51.828 Test[2434:c07] Response ==>
    2013-03-13 15:01:51.828 Test[2434:c07] (null)
    2013-03-13 15:01:51.829 Test[2434:c07] 0

  75. In the JSON Code was a little mistake and now come this fail:
    2013-03-13 14:32:49.014 Test[1720:c07] PostData: [email protected]&password=test
    2013-03-13 14:32:49.335 Test[1720:c07] Response code: 404
    (lldb)

  76. Okay, thanks for your answer.Now the mistakes are away.

    But in Xcode at “All Output” comes the following failure:

    2013-03-13 14:13:50.923 Test[99093:c07] PostData: [email protected]&password=test
    2013-03-13 14:13:51.388 Test[99093:c07] Response code: 200
    2013-03-13 14:13:51.389 Test[99093:c07] Response ==> Fehler
    2013-03-13 14:13:51.389 Test[99093:c07] (null)
    2013-03-13 14:13:51.389 Test[99093:c07] 0

    do you have an idea, why it’s so?

  77. Hi, thanks for this great tutorial.

    When I delete the code: – (void) alertStatus:(NSString *)msg :(NSString *)title
    {
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@”..”
    message:@”no”
    delegate:self
    cancelButtonTitle:@”Ok”
    otherButtonTitles:nil, nil];

    [alertView show];
    }

    When I delete this, I get the fail “No visible @interface for ‘ViewController’ declares the selector ‘alertStatus::’

    I hope you can help me.
    When I didn’t delete the code, in te simulator came always only the AlertView.

  78. hii….nice tutorial… well i want to check login credential for facebook or twitter kind of site. I want to implement login page which ask login through facebook. How to use the above code for this requirement. Thanks in advance.

  79. Hi mark,

    For the username/password input fields we need to assign an object to hold/access it.
    For the button, we need to assign an action which will be called when its clicked.

    Please watch the video. Thanks.

  80. Hi,

    When you say, 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.

    What do you exactly mean? Can you elaborate it in detail plz.

  81. Hi Ori Dahan, Did you solved the issue.Here is urgent requirement to solve the issue.

  82. No. Don’t put it into an array.
    Make it:
    {“message”:”Welcome To JSON”,”success”:1}

    and you could use the old code itself.
    NSInteger success = [(NSNumber *) [jsonData objectForKey:@”success”] integerValue];

  83. Yes, what changes you want me to do in the webservice?

    Do you want me to change the JSON to
    [login={“message”:”Welcome To JSON”,”success”:1}]

    But then how will the JSON processing work.

  84. Hi Dipin,

    I tried to replace the line, but it gives foll error

    No visible @interface for ‘NSDictionary’ declares the selector ‘objectAtIndex’

  85. Hi Dipin,

    Thanks a lot for this tutorial.

    When I run the app, on this line
    NSInteger success = [(NSNumber *) [jsonData objectForKey:@”success”] integerValue];

    I get the foll error

    JSON response from webservice:
    [{“message”:”Welcome To JSON”,”success”:1}]

    Console:
    2013-02-23 09:30:55.946 Json[2836:c07] -[__NSArrayM objectForKey:]: unrecognized selector sent to instance 0x76b6790
    2013-02-23 09:30:55.946 Json[2836:c07] Exception: -[__NSArrayM objectForKey:]: unrecognized selector sent to instance 0x76b6790

    Please Help Me..

  86. No, I did not find the solution yet.
    The login I try to implement had no JSON response because the encoding was wrong.
    After I changed the encoding I am getting a response but can’t login.
    Probably becuase the login I’m trying to implement is HTTP login, I’m currently trying to find another way to login (using NSURLConnection).
    Hope I will be able to do it

  87. Hi Ori Dahan, Exactly I am facing the same issue, trying to login to a website in ios app but no json response. I saw your ques in stack overflow. Did you overcome this issue, if so can you please send me the view controller.m file. Awaiting for your reply.

  88. Hi Dipin, Good Tutorial. It helped me a lot. I have one issue remained ,expecting your help in this issue. My url which I used is in the codeline

    NSURL *url=[NSURL URLWithString:@”https://dipinkrishna.com/jsonlogin.php”];

    is returning one URL. And I need to access the URL after the login with the secure code which is in that url. I think you got what I am willing to get from you.

  89. If you are asking about web sessions, then, yes it will persists. The cookies are saved.

    For the redirection: Do you have a navigation controller? If yes, then just push the new view into it.

  90. can you tell also about the sessions and redirection like i want to redirect to the new view when login sucess fully

  91. what if i want to change the link of login file from the live server to my localhost link ? is that work ? bcox i tried and it dont work

  92. Hi Dipin, I got error when I used the same code published by you. and the error is in the line

    in DKViewController.m file, alertStatus method

    –> if (tag) alert.tag = tag;
    (Semantic issue: use of undeclared Identifier: ‘alert’) .

    can You please check it out and help me in this regard.

  93. Lets add a tag to the alertView.
    Change the alertStatus method to:

    - (void) alertStatus:(NSString *)msg :(NSString *) title :(int) tag
    {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title message:msg delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        if (tag) alert.tag = tag;
        [alertView show];
    }

    And now pass in the tag to alertStatus.
    [self alertStatus:@”Logged in Successfully.” :@”Login Success!” :101];
    [self alertStatus:error_msg :@”Login Failed!” :0];

    And now update the alertView’s clickedButtonAtIndex method.

    1. - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
    2. {
    3.     if (alertView.tag == 101) {
    4.     {
    5.          [[UIApplication sharedApplication] openURL:[NSURL URLWithString: @"https://dipinkrishna.com"]];
    6.     }
    7. }

    There might be typos and bugs.
    Hope this helps.

  94. Hi Dipin Krishna, At first I am very thankful to you by responding with the code what I required. Thank you very much. After logged in successfully application is opening my URL. now one more issue is raised and the issue is here goes,

    when I give the wrong login credentials then invalid username/password pop up is displaying. up to that fine but when I click on ‘ok’ on the pop up again the application is redirecting to given URL. Our requirement is if we have wrong login credentials we can’t open the url to access. may I get the code how to resolve this issue

  95. Hi Sudheer,

    Add UIAlertViewDelegate to the interface of your view controller.
    In my example, change the @interface line in the file DKViewController.h to:

    1. @interface DKViewController : UIViewController <UIAlertViewDelegate> {}

    Then add the following code to the “.m” file.

    1. - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
    2. {
    3.     if(buttonIndex == 0)
    4.     {
    5.          [[UIApplication sharedApplication] openURL:[NSURL URLWithString: @"https://dipinkrishna.com"]];
    6.     }
    7. }

    This opens the url in safari.

    I haven’t tested this, there might be typos and bug.
    But, you could get an idea on what to do.

    Thanks for contacting.

  96. Hi Dipin Krishna, Today you saved my day. This tutorial helped me a lot. I had one doubt I need help 4m you in this regard. After access from the web service i.e logged in successfully pop up I would want to redirect into an external url(my application). may I know the procedure..
    awaiting for reply, thanks in advance

  97. Hello,

    Excellent tutorial. Thanks so much.

    One thing though,

    I can’t seem too get it to login successfully.
    I’ve followed your tutorial to the exact, but it’s just saying

    “Username and/or Password is invalid”

    Any suggestions? Thanks.

  98. Good Job Brother!

    I’m new in iOS development. Still dissecting each line of the loginClicked function though. Its very helpful to understand the logic and processes within it.

    Thanks a lot!

  99. Still not working, what else should I change except from the url?

    How can I know which parameters to change?

  100. If you are accessing https urls,
    Please add the below code to DKViewController.m, just below the import statements.

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

  101. Hello,

    Thanks for a great tutorial!

    I would like to use the above code in a specific website, how can I adjust the above code to work with it?
    I tried replacing the url in the following line with no luck:
    NSURL *url=[NSURL URLWithString:@”https://dipinkrishna.com/jsonlogin.php”];

    Can you help me adjust it properly?

    Thanks!

  102. Hi..I am new to iphone apps… this tutorial is very good. I need to redirect to a home page if the user name and password entered is correct. can u please suggest me code.

  103. Hi,

    You could use NSUserdefaults.

    Setting Value:
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    [prefs setInteger:1 forKey:@”isLoggedIn”];

    Retrieving Value:
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    NSInteger isLoggedIn = [prefs integerForKey:@”isLoggedIn”];

  104. Hello, great tutorial… How can I save the user credidentials in my app so the user doesn’t have to log in each time the app loads? If there is no user logged in, then I want the app to show the login page. If there is already a user logged in or upon successful login, I want to go to default app view. I then want to show a log out button that clears the user credidentials and goes back to login page… How can I do this? Thanks.

  105. Hi Dipin,

    I have UIImageView and an image has been added to it. This image view has been added to a view (which has a different background image).

    I need to rub/scratch the image so that it will be made transparent (like an eraser effect). I am using the below code to do it and the code works fine.

    – (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    lastTouch = [touch locationInView:bk]; // http://stackoverflow.com/questions/12329766/transparency-on-uiimageview-should-show-image
    NSLog(@”last touch is %@”, NSStringFromCGPoint(lastTouch));
    }

    – (void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    currentTouch = [touch locationInView:bk]; // bk is UIImageView
    NSLog(@”last touch is %@”, NSStringFromCGPoint(currentTouch));

    CGFloat brushSize = 35;
    CGColorRef strokeColor = [UIColor whiteColor].CGColor; // it’s like CGSize CGPoint structure..
    UIGraphicsBeginImageContext(bk.frame.size); // need to put scratch view??
    CGContextRef context = UIGraphicsGetCurrentContext();
    [bk.image drawInRect:CGRectMake(0, 0, bk.frame.size.width, bk.frame.size.height)];
    CGContextSetLineCap(context, kCGLineCapRound);
    CGContextSetLineWidth(context, brushSize);
    CGContextSetStrokeColorWithColor(context, strokeColor);
    CGContextSetBlendMode(context, kCGBlendModeClear);
    CGContextBeginPath(context);
    CGContextMoveToPoint(context, lastTouch.x, lastTouch.y);
    CGContextAddLineToPoint(context, currentTouch.x, currentTouch.y);
    CGContextStrokePath(context);
    bk.image = UIGraphicsGetImageFromCurrentImageContext(); // here the image will be becoming transparent
    UIGraphicsEndImageContext();
    lastTouch = [touch locationInView:bk];
    }

    How I do check if the image is completely transparent and the background image is fully visible? How can I keep track of this complete transparency of the first image?

    Please guide me.

    Cheers,
    Bharani 🙂

  106. No need brother….i have cured it
    excellent tutorial….really really hats off to u for ur selfless work
    keep going 🙂 🙂 🙂

  107. Hey i am getting an error on this line
    NSDictionary *jsonData = (NSDictionary *) [jsonParser objectWithString:responseData error:nil];

    the error says : no visible @interface for SBJsonParser declares the selecter ‘objectWithString:error’

    Please Help ME

  108. Hey i have created a project “registration”,with name,email amd password…that will post to a url using Post menthod,
    How can i create a login page for that dat,

    (i will mail you the project,registraion..please give me ur mail id)

    Please help…..

  109. NSJSONSerialization came with ios5. I haven’t used it till now.
    I don’t think that it would be anything different.
    I will prefer to use native library if and only if the class methods are easier and faster than the 3rd party libraries.

  110. Hi,
    Do you want to just authenticate using gmail username/password? (i.e check whether username/password exists.)
    Or
    Do you want to allow your application to access contents of a google account?

  111. Sorry to disturb again. Could you please share some tutorials / examples for integrating gmail login in iphone app? It’s bit urgent.. Can u help it out?

  112. Hi, Do we have an option of adding placeholder to UITextView using Interface Builder (like we’ll do it for UITextField)? If yes, please share it..

    Thanks,
    Bharani..

  113. Hi,

    I will be pretty difficult to do it without an api.

    What we can do is.
    1. Login into way2sms using the username and password by posting it to the login url.
    2. Now, the toughest part.
    a. Find out the url to which we can post the message, so that it will process the request.
    b. Find out the parameters that you will need to pass in.
    c. Post it.
    3. Process the HTML returned.

    🙂

  114. Hi…!! I’m planning to develop an iPhone app which should be integrated with Way2Sms (http://site2.way2sms.com/content/prehome.jsp?) /160By2 ( free messaging services to India). I couldn’t find any APIs related to it. Could you please guide me on this or provide any sample code? Thank you very much…!! Bharani….: )

  115. Hi.. The above problem is solved.. I just reinstalled the webserver and everything is working fine now.. Thanks….

  116. Hi.. I have followed your tutorial.. Everything worked well.. But I think I am having issues related to my webserver.. If I give http://localhost or http://127.0.0.1 or http://myComputerIpAddress in my browser, I am getting “It works”. But when I give http://127.0.0.1/anyFileName.php or http://myComputerIpAddress.php, I am getting “Not found.The requested URL /myFile.php was not found on this server.” But it works for http://localhost/myFile.php.

    Please help.
    Thanks for your time.

  117. Julian,

    Sorry. If you are not using https, just remove the below line from DKViewController.m

    [NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[url host]];

    Or if you are accessing https urls,
    Please add the below code to DKViewController.m, just below the import statements.

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

    🙂

  118. Hi there,

    First, thanks for posting all these tutorials.

    I”m getting “No known class method for selector ‘[NSURLRequest setAllowsAnyHTTPSCertificate:forHost.’

    Any idea how I can fix this?

    Thanks!

  119. It doesn’t maintain the sessions. You should store the session after the login gets successful. And the next time the app starts, look for a valid session. If present, skip the login screen or do a auto login.

    Thanks.

  120. Best explained login tutorial around, I have found so many sample projects but are not this well explained, great great job.

    One final question/request, does this maintains the session or what could I do in order for it to always open the app “as logged-in” instead of logging in on app start.

    Regards.

  121. Hi,

    thanks very much for the great tutorial.

    Are you considering to post the final part (5) sometime soon?

    Thanks,
    Tuna

Leave a note

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.