pathForResource returns nil in Mac OS X Console Application — Swift

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:

  1. Add the resource to your project.

enter image description here

  1. Select the project file in the project navigator.

enter image description here

  1. Add a new copy file phase.

enter image description here

  1. To the phase you added in step 3, add the file from step 1. You do this by clicking the + button (circled), and then navigating to the file in question.

enter image description here


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).

Tags:

Macos

Cocoa

Swift