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 coping to your app bundle. To fix it:
I added
file.txt
to my project and it was automatically added to theCopy Bundle Files
of my project. For me, I had to remove the extension from theforResource
and it worked.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 ofadd files
looks different for it does not show theAdd to targets
field:When inside a![enter image description here](https://i.stack.imgur.com/UkqMV.png)
.playground
file, instead press theHide or show the Navigator
button on the top-right of your Xcode window (visual impression)-->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:
I think you don't want the
inDirectory:
method. Try this instead:Double check the
Options
in theadd files
menu when adding the file. The target inAdd to targets
must be ticked to add it to the bundle:In case you are actually in another bundle (test for instance), use:
Click on your file on your navigation panel and open the Right Panel/ Property Inspector.
Ensure that you add to target membership