How to really URL encode an NSString in Objective-C, iPhone, etc.
Posted by Simon on April 22, 2009 at 02:52 AM
Categories: code, mac, iphone, objectivec
Trying to encode URL parameters on Mac or iPhone? Frustrated because NSString stringByAddingPercentEscapesUsingEncoding encodes non-URL characters but leaves the reserved characters (like slash / and ampersand &) alone? "Apparently" this is a "bug" apple is aware of, but they haven't done anything about it yet, and so, here is a solution that actually works.
Try this:
NSString * encodedString = (NSString *)CFURLCreateStringByAddingPercentEscapes(
NULL,
(CFStringRef)unencodedString,
NULL,
(CFStringRef)@"!*'();:@&=+$,/?%#[]",
kCFStringEncodingUTF8 );
As an example, @"'Decoded data!'/foo.bar:baz" will become "%27Decoded%20data%21%27%2Ffoo.bar%3Abaz".
Obviously you would use this, not on the full URL, but just on the parameters.
Comments
There are 13 comments on this post. Post yours →
Ah, thanks for that! It's a shame you have to fall back on CF, but hopefully it'll get fixed in NSString at some point...
This is awesome, thanks.
According to http://www.blooberry.com/indexdot/html/topics/urlencoding.htm and some other sources, I added some caracters in your list :
I want to add that most of the server still work with the "Percent Escapes" Table of Latin1
PHP urlencode function still works so
For example : é -> %E9 (with PHP urlencode)
é -> %C3%A9 (with kCFStringEncodingUTF8 as last parameter) é -> %E9 (with kCFStringEncodingISOLatin1 as last parameter)
So I modify the given function, with this parameter
Simon. You RULE. Thanks for taking the time to give your insights.
Bye!
thx, but I test it with your example string @"'Decoded data!'/foo.bar:baz", the result is 471684ecoded 0ata2270.000000foo.bar-0X1.FE638A05E9CCP+0baz, is it right ?
You 'da man! I've been trying to figure this out for days.
Make sure to NSLog( @"%@", encodedString); to get correct printout
Mansour,
NSLog(encodedString); will work fine for a NSString, no need to stuff it into another string.
Not if the string contains format specifiers.
Awesome, works a treat
Thankyou.
Thank you Simon! my plist embedded urls never looked better!
Post a comment
Required fields in bold.