Dov Dov - 5 months ago 12
Swift Question

How to encode a file NSURL to point to a file with a '/' in the name

I'm reading a file with a slash in its name. I can verify that it exists in the path where I'm looking for it, but creating an

from it fails. I've tried replacing the
with a
in the string I'm using to build the URL, but it didn't make a difference.

This is the code that constructs the URL:

let fileID = "This/That"
let filename = "\(fileID).json"

let bundleDirURL = myBundle.URLForResource("dirname", withExtension: nil, subdirectory: "MyFiles")
let fileURL = bundleDirURL.URLByAppendingPathComponent("Subpath").URLByAppendingPathComponent(filename)

let data = NSData(contentsOfURL: fileURL)

The list line is giving me a null data, even though the file exists in the correct path. I know it's the
that's tripping it up. How can I fix this? I need to keep the
in the filename.


/ is not actually a legal character in Darwin (OS X or iOS) file names. The UI just makes it look like it is in some cases. OS X exchanges : for /. So the actual name of your file is This:That. Depending on what tool you're using it will be rendered as either This:That or This/That. This is an old holdover from Mac OS 9. In Mac OS 9 and earlier, : is illegal, but / is legal. In Darwin (via OS X), the opposite is true.

You really, really want to avoid this situation if you can, and just not have / or : in your filenames (- and _ are generally safer, and . is often fine). But if you must, then you're going to have to swap it for : in your string.