Following is my PHP code that sends response to a webservice request :
$query = "select name,email,password from User where email='".$email."' AND password='".$password."'";
$result = mysql_query($query);
$num_rows = mysql_num_rows($result);
if($num_rows==1)
{
sendResponse(200, json_encode("match"));
}
if($num_rows==0)
{
sendResponse(204, json_encode("not match"));
}
Following is my iOS code:
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSString *status = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@" Returned Json data : %@",status);
if ([status isEqualToString:@"match"])
{
AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
[appDelegate OpenTabController];
}
//Boolean flag = [status isEqualToString:@"not match"];
//NSLog(@"flag : %d",flag);
if ([status isEqualToString:@"not match"])
{
NSLog(@"not match");
UIAlertView *alertView = [[UIAlertView alloc]
initWithTitle:@"Invalid email or password"
message:@""
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alertView show];
}
}
line [status isEqualToString:@"not match"]
doesn't work.
Guys I have found the solution:
php code:
if($num_rows==1)
{
$status = array(
"status" => "match",
);
sendResponse(200, json_encode($status));
}
if($num_rows==0)
{
$status = array(
"status" => "not match",
);
sendResponse(204, json_encode($status));
}
iOS Code:
NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error: nil];
NSString *status = [result objectForKey:@"status"];
NSLog(@"Returned Json data : %@",status);
You can try debugging and check what the value in status
is. I don't think there is any problem with string comparison in your code.
First You need to include the SBJson library to your project. Then import the json.h
#import "JSON.h"
Find the below code:
NSString *status = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSDictionary *dic = [status JSONValue];
This dictionary is your result.With this dictionary, you can check the value for your key.
PHP json_encode escaped space char. And it should make from 'not match' a json, like {'not match'}
First of all you are converting the string into a json repsonse. In your PHP code use the associative array to make a key value pair and then convert the data to JSON format in iOS using the JSON parser. Use objectForKey method on the converted dictionary
PHP Code
if($num_rows==1)
{
$status = "match";
$status_array = array("status"=>"$status");
sendResponse(200, json_encode($status_array));
}
if($num_rows==0)
{
$status = "not match";
$status_array = array("status"=>"$status");
sendResponse(204, json_encode($status_array));
}
iOS Code Use the process below to parse json and accordingly get the value as required. http://www.raywenderlich.com/5492/working-with-json-in-ios-5