How can I include a txt file in an Xcode project?

11Kilobytes picture 11Kilobytes · Dec 24, 2014 · Viewed 16.1k times · Source

I added a file "IntegerArray.txt" as follows, first I went to File -> Add file to "project name", I selected my file and it was copied into the root folder of my project, the same one that contains the .xcodeproj file. Then I clicked on my project's .xcodeproj file in Xcode, after which I went to Build Phases -> Copy Files -> "IntegerArray.txt", however when I build my project, the following code doesn't work

let bundle = NSBundle.mainBundle()
let path = bundle.pathForResource("IntegerArray", ofType: "txt")
println(path)

I expect to see the path to the file as output, but instead I see nil.

So I want to copy a file to my project in such a way that the above code works. How can I do this?

If I have a normal Cocoa Application, then when I add files they are automatically copied to the built program's bundle. However, with Command Line Tool's this doesn't seem to be the case, I'm starting to suspect a bug with Xcode.

Answer

jwlaughton picture jwlaughton · Dec 25, 2014

If you don't have a Resources directory in your project, select your project:

enter image description here

Then from the File Menu select Add Files:

enter image description here

In the window that opens click on the "New Folder" button in the lower left hand corner of the window.

A small pop-up window will open; type Resources in that window for the folder name then click the "Create" button. You should now have a Resources folder in your project.

Then the way I do it is to use Finder to copy the file into the Resources Directory of my project.

After the file is in the Resources Directory (in Finder), back in Xcode select the Resources directory in your project:

enter image description here

and use the File-> Add Files menu selection again. You should see your file highlighted (affineOutput.txt in this case):

enter image description here

Double Click on it and it will become part of the bundle.

As Milliways says, then check the Build Phases in your project to be sure the file is in the Copy Bundle Resources. If it's somewhere else, just drag it into the Copy Bundle Resources.