【问题标题】:Read a file in a macOS Command Line Tool project在 macOS 命令行工具项目中读取文件
【发布时间】:2017-10-05 05:30:24
【问题描述】:

我已将一些 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") }

此代码在基于视图的应用程序中使用时绝对正常,但总是在命令行工具中打印“找不到路径”。

有谁知道我做错了什么?

P.S:完全知道我应该为此使用 guard 语句,但代码不在函数中,只是在 main.swift 中胡闹,直到我弄明白为止。

【问题讨论】:

    标签: swift xcode bundle command-line-tool


    【解决方案1】:

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

    让我们开始吧:

    1. 在 Xcode 中,点击 File --> New --> Target...
    2. 点击顶部的ma​​cOS标签
    3. 向下滚动到Framework & Library,选择Bundle,点击Next。为新捆绑包命名(比如JSONMocks)。
    4. 将文件添加到此捆绑包。将文件添加到 Xcode,然后确保在其 target members 部分中勾选了 bundle:

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      猜你喜欢
      • 2018-10-15
      • 1970-01-01
      • 2017-05-10
      • 1970-01-01
      • 1970-01-01
      • 2021-08-30
      • 2019-07-08
      • 2018-03-23
      • 1970-01-01
      相关资源
      最近更新 更多