如何从URL字符串比较NSutf8stringencoding返回1或0与正常字符串@“1”(how

2019-08-03 21:17发布

我需要一个字符串从使用URL比较NSutf8stringencoding为了返回1或0,但它总是返回0,即使该字符串的值为1。

NSString *strURL = [NSString stringWithFormat:@"http://localhost/signup/login.php?username=%@&password=%@",username.text,password.text];

// to execute php code
NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURL]];

// to receive the returend value
NSString *strResult = [[NSString alloc] initWithData:dataURL 
encoding:NSUTF8StringEncoding];

// print the data in strResult
NSLog(@"%@",strResult);

if ([strResult isEqualToString:@"1"])
{
    // I need to get the control for main navigation controller 
    login2ViewController *controller = [[login2ViewController alloc] initWithNibName:@"login2ViewController" bundle:nil];
    controller.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    [self presentModalViewController:controller animated:YES ];

}else
{
    // invalid information
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"alert" message:@"Invalid Information" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
    [alert show];
    return;  
}

但它总是显示无效informartion即使在内容strResult1 。 我印刷由该值NSlog 。 从输出NSLog

2012-12-11 16:06:08.156 friend finder[277:11603] 
1

我如何可以比较该字符串@"1"

Answer 1:

试试下面的 - 有可能是在strResult额外的空格字符(比如回车):

if ([strResult rangeOfString:@"1"].length > 0) {
    // Do something...
}


Answer 2:

有可能在字符串中的字符。

使用

[strResult stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];


文章来源: how to compare a string from url to NSutf8stringencoding return 1 or 0 with normal string @“1”