2012-12-21 16 views
3

這是我的第一個問題在這裏:)如何在不接收錯誤響應的情況下與ObjectiveC中的服務器進行交互?

我真的需要幫助一些服務器和PHP的東西。這裏的問題:

我有一個NSMutableURLRequest與PHP文件這樣的交互:

NSInteger userID = 4; 

    NSString * logInString = [NSString stringWithFormat:@"id=%i&mode=HARD", userID]; 
    NSData * logInData = [logInString dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES]; 

    NSString *postLength = [NSString stringWithFormat:@"%d", [logInData length]]; 

    NSMutableURLRequest * logInRequest = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://myurl.lol/login.php"]]; 
    [logInRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; 
    [logInRequest setValue:postLength forHTTPHeaderField:@"Content-Length"]; 
    [logInRequest setHTTPMethod:@"POST"]; 
    [logInRequest setHTTPBody:logInData]; 

    [NSURLConnection sendAsynchronousRequest:logInRequest queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) { 
     if ([data length] >0 && error == nil) { 
      NSString * responseString = [NSString stringWithUTF8String:data.bytes]; 
      NSLog(@"%@", responseString); 
      [self performSelectorOnMainThread:@selector(responseWasReceived:) withObject:responseString waitUntilDone:YES]; 
     } 
     else if ([data length] == 0 && error == nil) { 
      [self performSelectorOnMainThread:@selector(didNotReceivedResponse) withObject:nil waitUntilDone:YES]; 
     } 
     else if (error != nil) { 
      [self performSelectorOnMainThread:@selector(errorDidOccurred) withObject:nil waitUntilDone:YES]; 

      NSLog(@"Error = %@", error); 
     } 
    }]; 

我的PHP是這樣的:

include("database.php"); 

if ($_REQUEST['mode'] == 'HARD') { 
    $query = mysql_query('SELECT COUNT(*) as total FROM users WHERE id = "' . $_REQUEST['id'] . '"'); 

    $fetch_username = mysql_fetch_object($query); 
    $usernames_coincidences = $fetch_username -> total; 

    if ($usernames_coincidences == 1) { 
     exit("ACCESS GRANTED"); 
    } else { 
     exit("USER DOES NOT EXIST"); 
    } 
} 

我應該得到「已授權訪問」串,有時會發生,但有時我也會收到像「ACCESS GRANTED」或「ACCESS GRANTEDOL」這樣的不良反應。

有什麼問題?你認爲我應該在方法中使用同步請求,並使用performSelector執行它:inBackground:?

回答

2

您試圖用原始數據構造responseString,原始數據不一定以NULL結尾。

取而代之的是:

[NSString stringWithUTF8String:data.bytes]; 

用這個代替:

[[NSString alloc] initWithBytes:data.bytes length:data.length encoding:NSUTF8StringEncoding]; 

請注意,我沒有考慮您是否使用ARC與否。您的原始呼叫產生了自動發放的價值;我的不是;確保你不會泄漏。

相關問題