Reputation: 1013
I've been trying to access a file in my command line tool Xcode project but program isn't able to find the file path. I'm assuming it's because the file isn't being copied to my project.
I've gone to build phases and added my file (graph2.net) but the program can't find the file.
func readGraph() {
if let path = Bundle.main.path(forResource: "graph2", ofType: "net") {
print(path)
} else {
print("Failed")
}
}
always returns failed. However in an iOS app, the option to copy bundle resources exists and I am able to find the file. How can I solve this issue?
Upvotes: 6
Views: 3230
Reputation: 6098
You can create a bundle and place it in same directory as your executable file.
import Foundation
private class BundleLocator {}
/// Category for easily retrieving the accompanying bundle.
extension Bundle {
/// Local bundle, assuming it resides in the main bundle.
static var resources: Bundle {
let executableBundle = Bundle(for: BundleLocator.self)
guard let bundlePath = executableBundle.path(forResource: "Resources", ofType: "bundle") else {
fatalError(
"Could not find Resources bundle. Make sure you copy the bundle to the same folder as the executable file."
)
}
guard let bundle = Bundle(path: bundlePath) else {
fatalError("Failed to create bundle from path: \(bundlePath)")
}
return bundle
}
}
Upvotes: 0
Reputation: 14875
A command-line-tool only consists of an executable. No bundle is created and what you are trying to do is not possible.
You’ll have to place the file in some other place and load it from there.
Upvotes: 10