I'm trying to create the login process (which is working at the moment) and at the same time, I would like to "load" user stats (those stats are in my database). I'm trying to use JSON, but I'm not an expert in this language and I need some help.
First, I would like to know if I'm doing this right, because it's not returning any value (NULL). You can see my PHP file, where is set the JSON code.
Is everything right? How can I pass the values using JSON to the xcode? Like I said, I need some help because I never used JSON and I'm not sure that I'm doing this right.
That's my login PHP file: (it launches when the user clics on the "LOGIN" button).
<?php
header('Content-type: application/json');
if($_POST) {
$DB_HostName = "localhost";
$DB_Name = "db";
$DB_User = "user";
$DB_Pass = "pass";
$userName = $_POST["username"];
$password = $_POST["password"];
$sql = "select * from user where userName = '$userName' and password = '$password';";
$con = mysql_connect($DB_HostName,$DB_User,$DB_Pass) or die(mysql_error());
mysql_select_db($DB_Name,$con) or die(mysql_error());
$res = mysql_query($sql,$con) or die(mysql_error());
$res1 = mysql_num_rows($res);
if ($res1>0)
{
//
$query = mysql_query("select * from user where userName = '$userName' and password = '$password';");
while ($row = mysql_fetch_array($query))
{
$id=$row['userID'];
}
$query2 = mysql_query("select * from user_stats where userID = '$id';");
while ($row2 = mysql_fetch_array($query2))
{
$followers=$row2['followers'];
$stars=$row2['stars'];
$photos=$row2['photos'];
$data=$followers.'-'.$stars.'-'.$photos;
}
//die(json_encode(array("message" => "Getting user information succeeded.", "status" => '"success":1', "data" => $data), JSON_PRETTY_PRINT));
//
echo '{"success":1,"data":'.$data.'}';
}
else
{
echo '{"success":0,"error_message":"Username and/or password is invalid.1"}';
}
}
else
{
echo '{"success":0,"error_message":"Username and/or password is invalid.2"}';
}
ViewController.m
- (IBAction)loginClicked:(id)sender {
@try {
if([[_txtUsername text] isEqualToString:@""] || [[_txtPassword text] isEqualToString:@""] ) {
[self alertStatus:@"Porfavor, introduce el usuario y contraseña" :@"Error"];
} else {
NSString *post =[[NSString alloc] initWithFormat:@"username=%@&password=%@",[_txtUsername text],[_txtPassword text]];
NSLog(@"PostData: %@",post);
NSURL *url=[NSURL URLWithString:@"http://autograpp.com/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);
NSString *data = [(NSNumber *) [jsonData objectForKey:@"data"] stringValue];
NSLog(@"%@",data);
if(success == 1)
{
NSLog(@"Login SUCCESS");
//[self alertStatus:@"Bienvenido a Autograpp." :@"Datos correctos"];
[self performSegueWithIdentifier:@"Main" sender:self];
} else {
NSString *error_msg = (NSString *) [jsonData objectForKey:@"error_message"];
[self alertStatus:error_msg :@"Datos incorrectos"];
}
/*
NSString *jsonString = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSData *JSONdata = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *jsonError = nil;
if (JSONdata != nil) {
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:JSONdata options:0 error:&jsonError];
if (jsonError == nil) {
// Set your text fields here.
NSLog(@"%@",dic);
}
}
*/
} else {
if (error) NSLog(@"Error: %@", error);
[self alertStatus:@"Ha ocurrido un problema inesperado" :@"Error"];
}
}
}
@catch (NSException * e) {
NSLog(@"Exception: %@", e);
[self alertStatus:@"Error." :@"Error"];
}
The problem is: When I try to read the values from the JSON they are NULL. I think it's because I'm not an expert using the JSON code and there is something wrong.
Thanks in advance.