1

I am using stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding to pass data to a php script. The problem is if the field has the char '&' in the text lets say: 'someone & cars', only the text "someone" is saved, everything after the '&' doesn't.

To create the string I use [NSString stringWithFormat:], so I have like 5 field in the form and if I use stringbyReplacingOcorrencesOfstring:@"&", what it does is replace the whole string not only the char '&' from the text field, so I get error.

Any ideas?

Matthias Bauch
  • 89,811
  • 20
  • 225
  • 247
Patrick
  • 21
  • 1
  • 4
  • 1
    possible duplicate of [Iphone SDk : Issue with ampersand in the URL string](http://stackoverflow.com/questions/705448/iphone-sdk-issue-with-ampersand-in-the-url-string) – matt Jan 17 '14 at 20:42
  • 1
    ASCII? What is this? 1980? Pray that the text never says "Es grünt so grün, wenn Spaniens Blüten blühen" ;-) Seriously: You should probably use UTF8 instead of ASCII. – Matthias Bauch Jan 17 '14 at 21:15
  • :) well, I'll use from now on for sure but it doesn't solve the problem. – Patrick Jan 17 '14 at 21:22

2 Answers2

6

Unfortunately, stringByAddingPercentEscapesUsingEncoding: doesn't actually escape all necessary URL characters.

Instead, you can use the lower-level CoreFoundation function:

(NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)myString, NULL, (CFStringRef)@"!*'\"();:@&=+$,/?%#[]% ", CFStringConvertNSStringEncodingToEncoding(encoding));

or, when using ARC:

CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(NULL, (__bridge CFStringRef)myString, NULL, (__bridge CFStringRef)@"!*'\"();:@&=+$,/?%#[]% ", CFStringConvertNSStringEncodingToEncoding(encoding)));

See this post for an example of a category on NSString that uses this function.

Léo Natan
  • 56,823
  • 9
  • 150
  • 195
James Frost
  • 6,960
  • 1
  • 33
  • 42
2

Following works using stringByAddingPercentEncodingWithAllowedCharacters if you want to specifically allow what would be encoded yourself. I'm using after base64 so this works fine.

NSString *charactersToEscape = @"!*'();:@&=+$,/?%#[]\" ";
NSCharacterSet *customEncodingSet = [[NSCharacterSet characterSetWithCharactersInString:charactersToEscape] invertedSet];

NSString *url = [NSString stringWithFormat:@"%@", @"http://www.test.com/more/test.html?name=john&age=28"];
NSString *encodedUrl = [url stringByAddingPercentEncodingWithAllowedCharacters:customEncodingSet];
CodeOverRide
  • 4,431
  • 43
  • 36