Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read file in Xcode project with Swift

Tags:

file

ios

swift

I made a method to read a file from the temporary folder. I use the following lines to get the document's path:

path = NSTemporaryDirectory().stringByAppendingPathComponent(folder)
path = path.stringByAppendingPathComponent(fileName + "." + fileType)

And it works great. My question is: how do I get the path for a file located in the main folders of the Xcode project? They are two text files that I drag and drop from a folder to the Xcode project. I selected the option "copy files if needed" when dropping the files. Thanks!

like image 734
Pablo Quemé Avatar asked Nov 29 '22 14:11

Pablo Quemé


2 Answers

What you are looking for is app's main bundle. You get a path of a file in it like this:

if let path = NSBundle.mainBundle().pathForResource(fileName, ofType:fileType) {
    // use path
}

Keep in mind this folder is read-only so you will need to copy the files to temp or documents folders if you want to make changes.

like image 99
Filip Radelic Avatar answered Dec 12 '22 02:12

Filip Radelic


Update the Swift 3.1 - Thanks @Filip Radelic

if let path = Bundle.main.path(forResource: fileName, ofType: fileType) {
    // use path
    print(path)
}
like image 28
Tuan Huynh Avatar answered Dec 12 '22 01:12

Tuan Huynh