Quantcast

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:
  1. CFURLCreateStringByAddingPercentEscapes(
  2.     NULL,
  3.     (CFStringRef)@“escape this %;/?:@&=+$[] string”,
  4.     NULL,
  5.     (CFStringRef)@“;/?:@&=+$,”,
  6.     kCFStringEncodingUTF8
  7. );

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…)

2 Responses to “url encode in cocoa”

  1. February 14th, 2007 | 5:07 pm

    Thanks for this tip! It was exactly what I needed.

  2. February 23rd, 2008 | 6:38 am

    [...] TikiRobot!, Mai Tais and Blinky Lights, Ahoy! ยป url encode in cocoa [...]

Leave a reply