Working on a command line tool, I am trying to retrieve the path of a list of words stored in a file called words.txt. The file is added to the project, included in the project's Target Membership, and selected to copy during the target's Copy Files build phase. Inside Main.swift this code:
if let path = NSBundle.mainBundle().pathForResource("words", ofType: "txt") {
println("Path is \(path)")
} else {
println("Could not find path")
}
prints "Could not find path". Is the mainBundle() class function the correct bundle to access? Any thoughts on why the the pathForResource function returns nil?
To use bundles with command line tools you need to make sure you're adding the resource files as part of the build phase. It sounds like you appreciate this, but haven't executed it correctly. The following worked for me in a quick demo app:
When you build the project, you should now be able to access the file's path using NSBundle
.
import Foundation
let bundle = NSBundle.mainBundle()
let path = bundle.pathForResource("numbers", ofType: "txt")
if let p = path {
let string = NSString(contentsOfFile: p,
encoding: NSUTF8StringEncoding,
error: nil)
println(string)
} else {
println("Could not find path")
}
// Output -> Optional(I am the numbers file.)
Command Line Tools do not use bundles, they are just a raw executable file and are not compatible with the copy files build phase or the NSBundle
class.
You will have to store the file somewhere else (eg, ~/Library/Application Support
).
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