如何在没有收到错误响应的情况下与Objective C中的服务器进行交互?

This is my first question here :)

I really need help with some servers and PHP stuff. Here's the question:

I have a NSMutableURLRequest that interacts with a php file like this:

    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);
        }
    }];

And my PHP is like this:

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

I should receive "ACCESS GRANTED" string, and sometimes it happens, but also sometimes I receive a bad response like "ACCESS GRANTED¿" or "ACCESS GRANTEDOL".

What's the problem? Do you think I should use Synchronous Request inside a method and perform it with performSelector:inBackground:?

You're attempting to construct responseString with raw data that is not necessarily NULL-terminated.

Instead of this:

[NSString stringWithUTF8String:data.bytes];

use this instead:

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

Note that I'm not taking into account whether you're using ARC or not. Your original call produced an autoreleased value; mine does not; be sure you don't wind up leaking.