Bundle.Main.Path(Forresource... Always Returns Nil When Looking for Xml File

Bundle.main.path(forResource... always returns nil when looking for xml file

Try this code:

if let filePath = Bundle.main.url(forResource: "config.xml", withExtension: nil, subdirectory: "/Resources") {

/// Do something with the filePath

}

Bundle.main.path(forResource: is always nil for files with accented chars in the name... is this a bug?

I expect that your filenames are not encoded in the same Unicode form. For example, LOWERCASE SMALL LETTER O + COMBINING ACUTE ACCENT is not the same as LATIN SMALL LETTER O WITH ACUTE, even though they look identical. Depending on how your filenames were created, there can be mismatches that are not "equal" in the way that Bundle treats equal. (They may be equal in the way that Swift.String treats equal, and still not be equal in the way that Bundle treats equal.)

Note that the filesystem on the device is not the same as the filesystem on the simulator, so things that work one place may not work another.

To explore this, start by using FileManager to enumerate the filenames in the directory. Then check their unicodeScalars property and compare that to the string you're looking for.

Be particularly suspicious of files that were not created and named on an Apple platform, since different platforms may have different default ways of encoding non-ASCII characters.


Based on your comments, your filenames are not UTF-8 encoded. They look like Latin1 (maybe created on Windows?)

My plist returns nil when I try to access it through the Bundle.main, but I know it's there

When you create Configuration.plist you are saving it to the Documents folder...

That folder is outside your app's bundle.

So, in your first code block, you're trying to load it from the bundle, which fails.

Your second code block correctly looks for and loads the file from the Documents folder.

file path in iOS 6 gives me null

Make sure your file is added to project's target. Choose your target then Build Phases->Copy Bundle Resources. The file should be there.

Sometimes it's worth cleaning your project and building from scratch. I have seen cases when file added wasn't copied to simulator/device until clean was performed.



Related Topics



Leave a reply



Submit