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

Read a file in a macOS Command Line Tool project

我已将几个 JSON 文件添加到我的 macOS 命令行工具项目中,但我似乎无法通过通常的方式找到它们。

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") }

此代码在基于视图的应用程序中使用时绝对正常,但总是在命令行工具中打印 "Could not find path"。

有人知道我做错了什么吗?

P.S:完全意识到我应该为此使用 guard 语句,但代码不在函数中,只是在 main.swift 中胡扯,直到我想出这个出。

没有命令行工具的应用程序包。只是一个二进制文件。

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

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

让我们开始吧:

  1. 在 Xcode 中,单击 文件 --> 新建 --> 目标...
  2. 单击顶部的 macOS 选项卡
  3. 向下滚动到 Framework & Library、select Bundle,单击下一步。为新包命名(假设 JSONMocks)。
  4. 将文件添加到此包中。将文件添加到 Xcode,然后确保在其 target membership 部分勾选了 bundle:

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

  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")!