[英]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.