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

2019-01-16 09:12发布

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.

9条回答
SAY GOODBYE
2楼-- · 2019-01-16 09:23

The issue is that the file isn't being coping 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.
查看更多
别忘想泡老子
3楼-- · 2019-01-16 09:24

I added file.txt to my project and it was automatically added to the Copy Bundle Files of my project. For me, I had to remove the extension from the forResource and it worked.

let path = Bundle.main.path(forResource: "file", ofType: "txt") // not forResource: "file.txt"
查看更多
三岁会撩人
4楼-- · 2019-01-16 09:26

Ah, so just found myself dealing with the exact same problem as the OP.

The problem is that the solutions given here and here do not work when the code is being executed in a playground, since the Options menu of add files looks different for it does not show the Add to targets field:

enter image description here

When inside a .playground file, instead press the Hide or show the Navigator button on the top-right of your Xcode window (visual impression)--> enter image description here

Then, once the Navigator folds open on the left-side of the Xcode window, simply drag & drop your file to the Resources directory of your playground.

If your setup looks anything like the following you should be ok:

enter image description here

查看更多
beautiful°
5楼-- · 2019-01-16 09:32

I think you don't want the inDirectory: method. Try this instead:

if let filepath = Bundle.main.path(forResource: "newTest", ofType: "txt") {
查看更多
Luminary・发光体
6楼-- · 2019-01-16 09:34

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")
}
查看更多
不美不萌又怎样
7楼-- · 2019-01-16 09:38

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

Ensure that you add to target membership

查看更多
登录 后发表回答