I know there are a few questions pertaining to this, but they're in Objective-C.
How can I access a .txt
file included in my app using Swift on an actual iPhone? I want to be able to read and write from it. Here are my project files if you want to take a look. I'm happy to add details if necessary.
Simply by searching in the app bundle for the resource
However you can't write to it because it is in the app resources directory and you have to create it in the document directory to write to it
now you can access it from fileURL
EDIT - 28 August 2018
This is how to do it in Swift 4.2
To create it in the document directory
Swift 3, based on Karim’s answer.
Reading
You can read files included in an app’s bundle through the bundle’s resource:
Writing
However, you can’t write there. You will need to create a copy, preferably in the Documents directory:
Example usage:
Bundles are read only. You can use
NSBundle.mainBundle().pathForResource
to access the file as read-only, but for read-write access you need to copy your document to Documents folder or tmp folder.Just a quick update for using this code with Swift 4:
And the following has been updated to account for writing the file out:
This particular example is not the most flexible, but with a little bit of work you can easily pass in your own file names, extensions and data values.
Bundles can be written. You can use
Bundle.main.path
to overwrite file by adding it intoCopy Bundles Resource
.