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.

Compatibility

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.

 

About the author

jayfuerstenberg I create software to scratch personal itches and then polish it for you to enjoy! I believe simple design is sexy, craftsmanship is a lost art in desperate need of a revival and that the old fashioned way of doing business is best. Armed with stockpiles of coffee and great feedback and trust earned from people like you, I intend on staying the course, righting the wrongs and getting a nice buzz all the while. By Jay Fuerstenberg Google+

Comments are Disabled