Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pathForResource returns nil in Mac OS X Console Application — Swift

Tags:

macos

swift

cocoa

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?

like image 716
MIGreenberg Avatar asked Jan 05 '15 00:01

MIGreenberg


2 Answers

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.)
like image 123
Paul Patterson Avatar answered Nov 01 '22 15:11

Paul Patterson


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

like image 30
Abhi Beckert Avatar answered Nov 01 '22 13:11

Abhi Beckert