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}';
}
?>