url encode in cocoa
Let’s say you need to url-encode a string. No problem! You can call uri_escape in perl, or urlencode in php, or urlencode in python, or CGI.escape in ruby…
But now let’s say you are writing in Cocoa. ugh. Before you shell out to your favorite scripting language, check out CFURLCreateStringByAddingPercentEscapes() It doesn’t encode the RFC 2396/RFC 2732 reserved characters by default (other than ‘[' and ']‘), but you can specify additional characters to encode in the fourth argument. Use something like this:
CODE:
-
CFURLCreateStringByAddingPercentEscapes(
-
NULL,
-
(CFStringRef)@“escape this %;/?:@&=+$[] string”,
-
NULL,
-
(CFStringRef)@“;/?:@&=+$,”,
-
kCFStringEncodingUTF8
-
);
It took me quite a while to figure this out… I found the NSString method stringByAddingPercentEscapesUsingEncoding, but that doesn’t escape the reserved characters.
(I have a suspicion that Cocoa developers are getting paid per letter…)

Thanks for this tip! It was exactly what I needed.
[...] TikiRobot!, Mai Tais and Blinky Lights, Ahoy! ยป url encode in cocoa [...]