1

我正在尝试在 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;
}
4

1 回答 1

5

基于帮助其他有类似情况的人,我会说问题在于来自服务器的响应不仅仅是 string "Yes"。很可能在文本之前和/或之后有一些空格。也许是一两个流浪的换行符。

尝试这个:

NSString *serverOutput = [[NSString alloc] initWithData:dataURL encoding: NSASCIIStringEncoding];
NSLog(@"Result = '%@'", serverOutput); // look for space between quotes
serverOutput = [serverOutput stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
于 2013-04-17T05:32:25.403 回答