密码与百分比符号总是错误的iPhone

时间:2012-01-12 13:34:53

标签: ios objective-c iphone login

我正在使用登录功能在Xcode中开发iPhone应用程序,我遇到以下代码时出现问题:

NSString *post = [NSString stringWithFormat:@"username=%@&password=%@",[NSString stringWithFormat:@"%@",username],password];
NSLog(post);

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding];
[request setHTTPMethod:@"POST"];
[request addValue:[NSString stringWithFormat:@"%@",username] forHTTPHeaderField:@"username"];
[request addValue:password forHTTPHeaderField:@"password"];
[request setHTTPBody:postData];
action = @"token";
NSURLConnection *connection;
connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];

现在有一个密码为%32dzs3 *的成员,应用程序总是会输出密码不正确的错误。当我NSLog密码时,它确实不是我在文本字段中输入的密码。它看起来像这样:50883393zs3 *。我也试过这个:

for(int i = 0; i < [password length];i++){
    if([password characterAtIndex:i] == '%'){
        NSString *temporarypw = [password substringWithRange:NSMakeRange(0, i)];
        password = [NSString stringWithFormat:@"%@%%%%%@",temporarypw,[password substringWithRange:NSMakeRange((i+1), (password.length - i -1))]];
        break;
    }
}

这会将密码返回为%%%% 32dzs3 *,并且当我对其进行NSLog时密码是正确的。当我运行请求时,响应仍然是错误的密码响应。我该如何解决这个问题?

2 个答案:

答案 0 :(得分:2)

%是HTTP网址中的特殊字符。您需要escape it before creating the URL:/#;@。幸运的是,NSStringmethod来执行此操作。

答案 1 :(得分:1)

您可能需要正确转义密码。看到这个问题: NSString method to percent escape '&' for URL