简体   繁体   中英

pathForResource returns nil in Mac OS X Console Application — Swift

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:

  1. Add the resource to your project.

在此输入图像描述

  1. Select the project file in the project navigator.

在此输入图像描述

  1. Add a new copy file phase .

在此输入图像描述

  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.

在此输入图像描述


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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM