URL Encoding In Objective C

A new project I’m working on uses NSURL to a great extent and as useful as that class is, it has one sour point.  It is unforgiving of improperly encoded strings when instantiating an NSURL via the URLWithString convenience constructor.

Naturally I needed an encoder that would escape the unsafe characters.  There is a decent selection online but they each lacked a few properties I need in my project.

  1. The domain + path portion needs to be left alone (no conversion of slashes etc…).
  2. Any previously escaped sequences (like %20) need to be left alone and not have the percent escaped again (like %2520).

I’ve given up looking for an existing solution and rolled my own, which I now share with you!

My implementation is called JFUrlUtil (Download) and is open sourced under the Apache license.


How it works

JFUrlUtil features a single public method called encodeUrl.  The approach it takes is basically to iterate over each character in the URL string you provide and escape where appropriate.  It is quite performant as it avoids invoking NSString’s stringByReplacingOccurrencesOfString:withString: method for each unsafe character.


I’ve tested this implementation against tens of thousands of URLs and have yet to find any encoded URL capable of causing NSURL to frown.  If you can find one I didn’t anticipate please let me know (jay@jayfuerstenberg.com) and I’ll gladly update my implementation.


Comments are Disabled