0

I'm trying to display an alert based on the data from PHP MySQL database using xcode 8. But when i entered a correct input, it does not run the block of "success = 1" statement. It always show else statement alert

ViewController.m

- (IBAction)loginbutton:(id)sender
{
    @try {
        if([[_email text] isEqualToString:@""] || [[_password text] isEqualToString:@""] ) {
            [self alertFailed:@"Please enter both Username and Password" :@"Login Failed!"];
        } else {
            NSString *post =[[NSString alloc] initWithFormat:@"email=%@&password=%@",[_email text],[_password text]];
            NSLog(@"PostData: %@",post);
            NSURL *url=[NSURL URLWithString:@"http://localhost/login.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);

                SBJsonParser *jsonParser = [SBJsonParser new];
                NSDictionary *jsonData = (NSDictionary *) [jsonParser objectWithString:responseData error:nil];
                NSLog(@"%@",jsonData);
                NSInteger success = [(NSNumber *) [jsonData objectForKey:@"success"] integerValue];
                NSLog(@"%ld",(long)success);
                if(success == 1) {
                    NSLog(@"Login SUCCESS");
                    [self alertStatus:@"Logged in Successfully." :@"Login Success!"]; 
                } else {
                    NSString *error_msg = (NSString *) [jsonData objectForKey:@"error_message"];
                    [self alertFailed:error_msg :@"Login Failure! Correct your credentials"];
                } 
            } else {
                if (error) NSLog(@"Error: %@", error);
                [self alertFailed:@"Connection Failed" :@"Login Failed!"];
            }
        }
    }
    @catch (NSException * e) {
        NSLog(@"Exception: %@", e);
        [self alertStatus:@"Login Failed." :@"Login Failed!"];
    }
}//End click function

test.php

<?php
    $connect = mysqli_connect("localhost", "root", "root", "db");
    global $connect;   

    if(isset($_POST['email']) && isset($_POST['password'])) {
        if( $_POST['email'] == 'abc' &&  $_POST['password'] == '123' ) {
            echo '{"success":1}';
        } else {
            echo '{"success":0}';
        }
    } else {
        echo '{"success":0}';
    }    
?>
Cœur
  • 37,241
  • 25
  • 195
  • 267
AlotJai
  • 147
  • 4
  • 18
  • What does `` return? – Cagy79 Jan 03 '17 at 10:40
  • {"success":1}mysqli Object ( [affected_rows] => 0 [client_info] => mysqlnd 5.0.12-dev - 20150407 - $Id: 241ae00989d1995ffcbbf63d579943635faf9972 $ [client_version] => 50012 [connect_errno] => 0 [connect_error] => [errno] => 0 [error] => [error_list] => Array ( ) [field_count] => 0 [host_info] => Localhost via UNIX socket [info] => [insert_id] => 0 [server_info] => 5.6.33 [server_version] => 50633 [stat] => Uptime: 443671 Threads: 1 Questions: 6923 Slow queries: 0 Opens: 91 Flush tables: 1 Open tables: 84 Queries per second avg: 0.015 – AlotJai Jan 03 '17 at 10:46
  • What is the output of NSDictionary jsonData? Try to set a breakpoint and type `po jsonData` to the Debugger. Also try valueForKey instead of objectForKey – Gulliva Jan 03 '17 at 10:56
  • Sorry, i'm not sure how to do that. I'm new in iOS development . . – AlotJai Jan 03 '17 at 11:03

2 Answers2

1

Try like following way:

    if([_email.text && _email.text.length==0] || [_password.text && _password.text.length==0]) {
        [self alertFailed:@"Please enter both Username and Password" :@"Login Failed!"];
    }
    else 

{
NSString *post =[[NSString alloc] initWithFormat:@"email=%@&password=%@",_email.text,_password.text];
            NSLog(@"PostData: %@",post);

            NSURL *url=[NSURL URLWithString:@"http://localhost/login.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);

                SBJsonParser *jsonParser = [SBJsonParser new];
                NSDictionary *jsonData = (NSDictionary *) [jsonParser objectWithString:responseData error:nil];
                NSLog(@"%@",jsonData);
                NSInteger success = [(NSNumber *) [jsonData valueForKey:@"success"] integerValue];
                NSLog(@"%ld",(long)success);
                if(success == 1)
                {
                    NSLog(@"Login SUCCESS");
                    [self alertStatus:@"Logged in Successfully." :@"Login Success!"];

                } else {

                    NSString *error_msg = (NSString *) [jsonData valueForKey:@"error_message"];
                    [self alertFailed:error_msg :@"Login Failure! Correct your credentials"];
                }

            } else {
                if (error) NSLog(@"Error: %@", error);
                [self alertFailed:@"Connection Failed" :@"Login Failed!"];
            }
        }
    }

Update

Add following code in your info.plist

right click on info.plist--> click to source code--> and add following code:

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>
Suraj Sukale
  • 1,778
  • 1
  • 12
  • 19
  • Thanks for the reply. But what i want to achieve is in this block of statement. if(success == 1) { NSLog(@"Login SUCCESS"); [self alertStatus:@"Logged in Successfully." :@"Login Success!"]; } – AlotJai Jan 03 '17 at 11:02
  • check my updated answer brother and let me know where is the problem? – Suraj Sukale Jan 03 '17 at 11:14
  • still not work ... the output show "NSLocalizedDescription=The resource could not be loaded because the App Transport Security policy requires the use of a secure connection.}" – AlotJai Jan 03 '17 at 11:26
  • sorry . i went off work yesterday. i'll try your suggestion . i'll let you know later. thank btw :) – AlotJai Jan 04 '17 at 00:40
  • Still not working. Already add NSAppTransportSecurity into info.plist. Code can run inside the if ([response statusCode] >=200 && [response statusCode] <300) . But it always run 'else' statement. It does not catch "if(success == 1)" – AlotJai Jan 04 '17 at 02:46
  • The html output in xcode always show "sampleJson2[58817:1015413] (null)" and "sampleJson2[58817:1015413] 0" . – AlotJai Jan 04 '17 at 02:48
  • what is output of NSLog(@"%ld",(long)success); ? – Suraj Sukale Jan 04 '17 at 04:23
  • log output is 1 and then 0 ... it turns out that i need to exit(); the code in PHP to allow the code to execute perfectly in xcode . Your code work like a charm . Thanks. . :) – AlotJai Jan 04 '17 at 05:39
  • Glad, i could help.all the best :) – Suraj Sukale Jan 04 '17 at 06:11
  • Thanks again :) . . Btw, can you help me on this question ? http://stackoverflow.com/questions/41476633/how-to-bring-textfield-value-into-other-viewcontroller-in-x-code-obj-c – AlotJai Jan 05 '17 at 02:54
  • @AlotJai I uploaded answer of that question there, please check and get back to me if you still suffering from any issue.. :) – Suraj Sukale Jan 05 '17 at 08:02
  • Hi, thanks for the feedback . . It work like a charm. . . I have this new question, can you take a look on it ? Thanks .. http://stackoverflow.com/questions/41498184/how-to-get-data-from-php-mysql-using-x-code-8-objective-c – AlotJai Jan 06 '17 at 02:54
  • Opss. . here's the new question . The above question link i already got an answer . . new one is http://stackoverflow.com/questions/41498453/display-get-data-from-php-mysql-in-x-code-8-objective-c – AlotJai Jan 06 '17 at 03:57
  • @AlotJai I answered that question also bro, please upvote and accept my answer if its works for you..because it may be helpfu for other user also. :) – Suraj Sukale Jan 06 '17 at 04:52
0

Try this, this is the new way with NSURLSession. It tried it and it works for me.

NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];

    NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:@"http://localhost/login.php"]];
    [request setHTTPMethod:@"POST"];
    NSString *data = [NSString stringWithFormat:@"email=%@&password=%@",_email.text,_password.text];

    [request setHTTPBody:[NSData dataWithData:[data dataUsingEncoding:NSUTF8StringEncoding]]];
    NSURLSessionTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSHTTPURLResponse *resp = (NSHTTPURLResponse *)response;
        if(resp.statusCode==200){
            NSString *dataString = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
            NSError *jsonError;
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&jsonError];
            NSInteger number = [(NSNumber*)[dict valueForKey:@"success"] integerValue];
            if(number==1){
                NSLog(@"Login Success");
            }else{
                NSLog(@"Login Failed");
            }
        }
    }];
    [dataTask resume];

Also you have to add the Property to your Info.plist which allows you to load HTTP Connections.

enter image description here

Gulliva
  • 488
  • 2
  • 10