本文介绍了为什么isEqualToString不适用于NSString?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在XCode中为iPhone应用程序编写登录过程。问题是在NSString serverOutput下面。当我使用printf(serverOutput.UTF8String)打印它;它会打印是到控制台。但是,当我将serverOutput比较为Yes时,它不工作。任何帮助将不胜感激。这是我的代码:

I am trying to code the login process for an iPhone app in XCode. The problem is with the NSString serverOutput below. When I print it using printf(serverOutput.UTF8String); it prints 'Yes' to the console. However when I compare serverOutput to "Yes" it doesn't work. Any help would be appreciated. Here's my code:

- (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;
}


推荐答案

情况我会说的问题是,服务器的响应不只是字符串。很可能在文本之前和/或之后有一些空格。

Based on helping others with similar situations I would say the problem is that the response from the server isn't just the string "Yes". Most likely there is some whitespace before and/or after the text. Perhaps a stray newline or two.

尝试以下操作:

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

这篇关于为什么isEqualToString不适用于NSString?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-19 06:11