Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 667
Zakarius Jay Poggenpohl Avatar asked Jan 21 '17 03:01

Zakarius Jay Poggenpohl


2 Answers

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.
like image 153
Denis Hennessy Avatar answered Oct 17 '22 04:10

Denis Hennessy


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")
}
like image 41
shallowThought Avatar answered Oct 17 '22 04:10

shallowThought