在macOS命令行工具项目中读取文件

Xma*_*hts 10 xcode bundle command-line-tool swift

我在我的macOS命令行工具项目中添加了一些JSON文件,但我似乎无法通常的方式找到它们.

if let path = Bundle.main.path(forResource: "Data", ofType: "json")
{
    if let contents = try? String(contentsOfFile: path)
    {
        print (contents)
    }
    else { print("Could not load contents of file") }
}
else { print("Could not find path") }
Run Code Online (Sandbox Code Playgroud)

在基于视图的应用程序中使用时,此代码可以正常工作,但始终在命令行工具中打印"无法找到路径".

有谁知道我做错了什么?

PS:完全清楚我应该使用guard这个语句,但代码不在函数中,只是在main.swift中讨论,直到我弄明白这一点.

Eri*_*ric 10

您可以创建一个单独的包,将文件放在那里,然后加载它们,而不必担心它们各自的 URL。

我们开始做吧:

  1. 在 Xcode 中,单击文件 --> 新建 --> 目标...
  2. 单击顶部的macOS选项卡
  3. 向下滚动到Framework & Library,选择Bundle,单击 Next。为新包命名(比方说JSONMocks)。
  4. 将文件添加到此包中。将文件添加到 Xcode,然后确保在其目标成员资格部分勾选了该包:

    捆绑文件的目标成员资格

  5. 将捆绑包添加到您的目标。在目标的 Build Phases 中,打开Copy Files阶段并单击+按钮。选择捆绑包并单击添加

    在此处输入图片说明

  6. 以编程方式访问包的内容,因此:

let currentDirectoryURL = URL(fileURLWithPath: FileManager.default.currentDirectoryPath)
let bundleURL = URL(fileURLWithPath: "JSONMocks.bundle", relativeTo: currentDirectoryURL)
let bundle = Bundle(url: bundleURL)
let jsonFileURL = bundle!.url(forResource: jsonFileName, withExtension: "json")!
Run Code Online (Sandbox Code Playgroud)


Lou*_*nco 7

命令行工具没有应用程序包.只是二进制.

您需要将JSON文件放在已知位置(当前目录?)并自己构建路径

  • http://stackoverflow.com/questions/31480186/get-path-to-swift-script-from-within-script (2认同)