URL path retrieval cheat sheet

As Cocoa developers, there's quite a broad range of APIs available to us for pulling out the path component of a URL. I often forget the particular quirks of them, so here's a handy cheat sheet to bring all that together. Who knows, maybe you'll even learn of some new API here.

-[NSURL path] CFURLCopyPath() CFURLCopyPathStrict() NSURLComponents
Decodes percent escapes✗ (the docs are wrong)has API for both
Strips trailing slash
Strips leading slash
Includes parameter string
Resolves file reference URLs
Resolves against base URL✓ (-relativePath doesn't)specify when creating

Known bugs

If you happen to have a URL whose path looks like it could form a file reference, but where the scheme isn't file, -[NSURL path] will still attempt to resolve it. e.g. test:///.file/test. Other APIs do not suffer this bug. (radar://14141744)

Parameter strings

Parameter strings are a fairly rarely used feature of the URL syntax. A quick example:


NSURL and CFURL have dedicated APIs for retrieving that (e.g. -parameterString). NSURLComponents instead lumps that in as part of the path.

Failed file reference resolution

As noted above, -path attempts to resolve file reference URLs back into regular paths. This can fail, due to things like the target file having been removed from the disk. Failure is indicated by returning nil (I wrote up before how to get some error info if this happens). So be a little wary of that if there's a chance your code could have to deal with file reference URLs.

© Mike Abdullah 2007-2015