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:
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")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With