我正在尝试为XCode中的iPhone应用程序编写登录过程。问题在于下面的NSString serverOutput。当我使用printf(serverOutput.UTF8String)打印它时;它向控制台打印“是”。但是,当我将serverOutput与“是”进行比较时,它不起作用。任何帮助,将不胜感激。这是我的代码:
- (IBAction) loginButton: (id) sender
{
// TODO: spawn a login thread
indicator.hidden = FALSE;
[indicator startAnimating];
NSString *post =[NSString stringWithFormat:@"username=%@&password=%@",userName.text, password.text];
NSString *hostStr = @"http://10.243.1.184/connectDB.php?";
hostStr = [hostStr stringByAppendingString:post];
NSData *dataURL = [NSData dataWithContentsOfURL: [ NSURL URLWithString: hostStr ]];
NSString *serverOutput = [[NSString alloc] initWithData:dataURL encoding: NSASCIIStringEncoding];
printf(serverOutput.UTF8String);
if([serverOutput isEqualToString:@"Yes"]){
UIAlertView *alertsuccess = [[UIAlertView alloc] initWithTitle:@"Congrats" message:@"You are authorized"
delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
[alertsuccess show];
[alertsuccess release];
}
else {
UIAlertView *alertsuccess = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Username or Password Incorrect"
delegate:self cancelButtonTitle:@"OK"otherButtonTitles:nil, nil];
[alertsuccess show];
[alertsuccess release];
//[self.navigationController pushViewController:DashboardViewController animated:YES];
loginbutton.enabled = TRUE;
}
loginbutton.enabled = FALSE;
}
答案 0 :(得分:5)
基于帮助处于类似情况的其他人,我会说问题是来自服务器的响应不仅仅是字符串"Yes"
。很可能在文本之前和/或之后有一些空格。也许是一两个流浪的新行。
试试这个:
NSString *serverOutput = [[NSString alloc] initWithData:dataURL encoding: NSASCIIStringEncoding];
NSLog(@"Result = '%@'", serverOutput); // look for space between quotes
serverOutput = [serverOutput stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];