4

I have been having some problem with the stringByAddingPercentEscapesUsingEncoding: method. Here's what happens:

When I try to use the method to convert the NSString:

"..City=Cl&PostalCode=Rh6 0Nt"

I get this this..

"City=Cl&PostalCode=Rh62t"

It should be:

"..City=Cl&PostalCode=Rh6%200Nt"

What can I do about this? Thanks in advance !!

Mike Abdullah
  • 14,933
  • 2
  • 50
  • 75
Susanth
  • 61
  • 1
  • 1
  • 5
  • Might help if your strings either consistently started with ".." or not. It also works for me on iOS 4 (`(gdb) print- [@" 0" stringByAddingPercentEscapesUsingEncoding:4]` prints `%200`) – tc. Jun 29 '10 at 12:23

2 Answers2

31

For me, this:

NSString *s=[@"..City=Cl&PostalCode=Rh6 0Nt" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(@"s=%@",s);

... outputs:

s=..City=Cl&PostalCode=Rh6%200Nt

You're most likely using the wrong encoding.

TechZen
  • 64,370
  • 15
  • 118
  • 145
  • Thanks for the reply. Yea, I realized a dumb mistake in my NSLog.. I had NSLog the string encoded string by NSLog(str) instead of NSLog(@"%@",str) and that had caused the incorrect output on my Console. Thanks! – Susanth Jun 30 '10 at 09:00
  • 3
    It's good idea to always post your logging code so others can see and catch these types of errors. Everyone makes them and for some reason they're hard to see if you're the one who wrote the code. – TechZen Jun 30 '10 at 12:52
  • @TechZen stringByAddingPercentEscapesUsingEncoding this method only for space or all special characters. – prabu Oct 31 '13 at 07:42
0

This happens when you're trying to encode to NSASCIIStringEncoding a string with characters not supported by ASCII.

Make sure you're encoding to NSUTF8StringEncoding, if the string can contain UTF8 characters or the method would return nil.

Kof
  • 23,893
  • 9
  • 56
  • 81