2

I'm developing an iPhone application in Xcode with a login function and I'm having trouble with the following code:

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

Now there is a member with the password %32dzs3* and the app always gives an error that the password is incorrect. When I NSLog the password it's indeed not the password I typed in the textfield. it looked like this: 50883393zs3* . I also tried this:

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

this returns the password as %%%%32dzs3* and the password is right when I NSLog it. still the response is a wrong password response when I run the request. How can I fix this?

easwee
  • 15,757
  • 24
  • 60
  • 83
Kjeld
  • 83
  • 8
  • You mean in your application, the password is sent in clear text and not escaped? Ouch. I don't want to be one of your users. – jv42 Jan 12 '12 at 13:59

2 Answers2

2

% is a special character in HTTP URLs. You need to escape it before creating the URL, also :, /, #, ;, and @. Fortunately NSString has a method to do it.

JeremyP
  • 84,577
  • 15
  • 123
  • 161
1

You probably need to escape the password correctly. See this question: NSString method to percent escape '&' for URL

Community
  • 1
  • 1
Felix Lamouroux
  • 7,414
  • 29
  • 46