繁体   English   中英

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

[英]How can I interact with a server in ObjectiveC without receiving a wrong response?

这是我的第一个问题:)

我真的需要一些服务器和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”字符串,有时会发生这种情况,但有时候我会收到“ACCESSGRANTED¿”或“ACCESS GRANTEDOL”这样的错误回复。

有什么问题? 你认为我应该在方法中使用同步请求并使用performSelector执行它:inBackground:?

您正在尝试使用不一定以NULL结尾的原始数据构造responseString

而不是这个:

[NSString stringWithUTF8String:data.bytes];

改用它:

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

请注意,我不会考虑您是否使用ARC。 您的原始通话产生了自动释放的价值; 我的没有; 请确保你没有泄漏。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM