2013-06-06 25 views
0

以下是我的PHP代碼發送響應Web服務請求:字符串等於沒有工作的iOS

$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")); 
} 

以下是我的iOS代碼:

-(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]; 

    } 
} 

[status isEqualToString:@"not match"]不起作用。

+0

你有沒有轉換從Web服務的JSON響應中mainuplated成iOS代碼? –

+0

是的,我做到了。 NSString * status = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@「返回的Json數據:%@」,狀態); –

+0

並且打印出您期望的消息? – Eric

回答

1

傢伙,我已經找到了解決辦法:

PHP代碼:

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代碼:

NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error: nil]; 

NSString *status = [result objectForKey:@"status"]; 
NSLog(@"Returned Json data : %@",status); 
0

您可以嘗試調試並檢查status中的值是什麼。我認爲你的代碼中沒有任何字符串比較問題。

0

首先您需要將SBJson庫包含到您的項目中。 然後導入json.h

#import "JSON.h" 

找到下面的代碼:

NSString *status = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; 
NSDictionary *dic = [status JSONValue]; 

這本字典是你result.With本字典,你可以檢查你的關鍵價值。

0

PHP json_encode轉義空格char。 它應該從'不匹配'一個JSON,如{'不匹配'}

2

首先,你將字符串轉換成json repsonse。在您的PHP代碼中,使用關聯數組創建鍵值對,然後使用JSON解析器將數據轉換爲iOS中的JSON格式。使用objectForKey方法對轉換後的字典

PHP代碼

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代碼 使用下面的過程來解析JSON並據此要求獲得的價值。 http://www.raywenderlich.com/5492/working-with-json-in-ios-5