(Properly) introducing KSURLComponents

I've mentioned KSURLComponents in passing before, but never given it a proper introduction. Now that iOS 7 has been released, I can reveal the truth: it's pretty much a straight-up clone of NSURLComponents with the intent to support older OS releases.

NSURLComponents is one of my favourite new APIs in iOS 7. We do quite a lot of URL manipulation in Sandvox, which tends to result in an awful lot of utility methods for NSURL. I've long considered writing a dedicated class to help with this, but been torn between two options which can probably be best summarised:

  • MutableURL
  • URLComponents


I daresay Apple faced this same decision. NSMutableURL initially makes the most sense as a companion to all the NSMutableFoo classes in Foundation. But closer inspection reveals the awkward problem that many mutations cannot result in a valid URL. For example, trying to specify a relative path is only allowed if there's no scheme or authority component. That then leaves our theoretical NSMutableURL class with having to throw exceptions, throw away data, or exist in some unusual invalid state when such a mutation is requested. And don't even get started on handling URL schemes that don't conform to RFC 1808

Instead, NSURLComponents — along the same lines as NSDateComponents — probably makes the most sense. All mutations are legal, and -URL will simply return nil until a valid combination of components is specified.

Of course NSURLComponents isn't much good to us in Sandvox yet, since it doesn't exist on OS X 10.6. And so I decided to simply create my own clone in the form of KSURLComponents. There's just a couple of minor differences at present:

  • Percent-encoded properties are read-only, to save me writing the code for sanity checking in the setter methods. If you particularly need this let me know and I'll look at adding it. Even better if you can send a pull request!
  • Properties are non-atomic. To my mind there's no benefit in atomic properties here, since sharing instances across threads/queues is almost certainly a bad idea. Clients can perform their own synchronisation if absolutely desired.


Both of these probably make my implementation fractionally faster than Apple's, but I expect that's of no real-world consequence.

Annoyingly, there's no published documentation for NSURLComponents yet it seems, so I can't link to it! Fortunately CocoaDocs should have your back here with the KSURLComponents API (semi-documented so far).

Anyway, please enjoy the code. It's MIT licensed. KSURLComponents lives inside our KSFileUtilities repository, but doesn't depend on any of the other classes in there, so you get to pick exactly what you need.

© Mike Abdullah 2007-2015