【问题标题】:Why does isEqualToString not work for NSString?为什么 isEqualToString 不适用于 NSString?
【发布时间】:2013-04-17 05:27:34
【问题描述】:

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

【问题讨论】:

    标签: objective-c xcode nsstring compare


    【解决方案1】:

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

    试试这个:

    NSString *serverOutput = [[NSString alloc] initWithData:dataURL encoding: NSASCIIStringEncoding];
    NSLog(@"Result = '%@'", serverOutput); // look for space between quotes
    serverOutput = [serverOutput stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    

    【讨论】:

    • 顺便说一句 - 当您将用户名和密码添加到 URL 时,您需要正确转义它们。否则,用户名或密码包含某些字符的人会导致问题。另外,我希望你计划在你的最终应用程序中使用https。不要通过常规 http 以纯文本形式发送用户名和密码。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-06
    • 1970-01-01
    • 1970-01-01
    • 2011-10-25
    • 1970-01-01
    • 2017-05-08
    • 1970-01-01
    相关资源
    最近更新 更多