Bundle.main.path(forResource:ofType:inDirectory:) returns nil

Try not to laugh or cry -- I'm just getting back into coding after 20 years out...

I've spent more than 4 hours looking at references and trying code snippets to get Bundle.main.path to open my text file so I can read in data for my app (my next step is to appropriately parse it).

if let filepath = Bundle.main.path(forResource: "newTest", ofType: "txt")
{
    do
    {
        let contents = try String(contentsOfFile: filepath)
        print(contents)

    }
    catch
    {
        print("Contents could not be loaded.")
    }
}
else
{
    print("newTest.txt not found.")
}

The result is: "newTest.txt not found." regardless of how I try to drag&drop the file into the project, create the file inside Xcode or use the File -> Add Files to ... menu item.


The issue is that the file isn't being copied to your app bundle. To fix it:

  • Click your project
  • Click your target
  • Select Build Phases
  • Expand Copy Bundle Resources
  • Click '+' and select your file.

Double check the Options in the add files menu when adding the file. The target in Add to targets must be ticked to add it to the bundle:

In case you are actually in another bundle (test for instance), use:

guard let fileURL = Bundle(for: type(of: self)).url(forResource: fileName withExtension:"txt") else {
        fatalError("File not found")
}

Click on your file on your navigation panel and open the Right Panel/ Property Inspector.

enter image description here

Ensure that you add to target membership


It's crazy how much time such a simple problem can cost.

Some answers here helped me but I always tried:

Bundle.main.url(forResource: selectedTitle, withExtension: "mp3")

For some reason that doesn't work, but getting the path and translating it to a URL afterwards works:

let path = Bundle.main.path(forResource: selectedTitle, ofType: "mp3")
let url = URL(fileURLWithPath: path!)