Why does isEqualToString not work for NSString?

2019-01-26 01:49发布

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

1条回答
闹够了就滚
2楼-- · 2019-01-26 02:25

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.

Try this:

NSString *serverOutput = [[NSString alloc] initWithData:dataURL encoding: NSASCIIStringEncoding];
NSLog(@"Result = '%@'", serverOutput); // look for space between quotes
serverOutput = [serverOutput stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
查看更多
登录 后发表回答