Guaranteeing directory URLs

-[NSURL URLByAppendingPathComponent:] has a hidden superpower! It can give you a URL whose path is a directory — guaranteed!

Alright, maybe it's not all that hidden. The docs say:

If the original URL does not end with a forward slash and pathComponent does not begin with a forward slash, a forward slash is inserted between the two parts of the returned URL

And I suppose as superpowers go, that's pretty weak sauce. Perhaps it's just a "power"?

Anyway, how do you get at this? Simple, just pass in an empty string for the path component, like so:

This happily handles URLs containing components after the path, such as a query, by keeping them in the newly generated directory URL.

Tested on OS X v10.7 – 10.9, using unit tests in KSFileUtilities. So if Apple somehow break it in future, I'll get early warning and update this post.

If you particularly need efficiency, could call CFURLHasDirectoryPath() first to see if a new URL is actually needed.

Update:

Turns out there is one caveat you might need to be aware of. It turns out that if the URL is a file: one and corresponds to a real directory on disk, you’ll end up with a double terminating slash like so:

file:///Users/Shared => file:///Users/Shared//

I have a sneaky suspicion something internally is calling through to +fileURLWithPath: which is documented to detect that Shared is a directory and append a slash to the path, before the extra slash gets tacked on.

© Mike Abdullah 2007-2015