ios - Bundle.main.path(forResource :ofType:inDirectory:) returns nil

标签 ios swift macos file swift3

尽量不要笑或哭——我在 20 年后才重新开始编码......

我花了 4 个多小时查看引用资料并尝试使用代码片段来获取 Bundle.main.path 打开我的文本文件,这样我就可以读取我的应用程序的数据(我的下一步是适本地解析它)。

if let filepath = Bundle.main.path(forResource: "newTest", ofType: "txt")
{
    do
    {
        let contents = try String(contentsOfFile: filepath)
        print(contents)

    }
    catch
    {
        print("Contents could not be loaded.")
    }
}
else
{
    print("newTest.txt not found.")
}

结果是:“找不到 newTest.txt。”无论我如何尝试将文件拖放到项目中,在 Xcode 中创建文件或使用 File -> Add Files to ... 菜单项。

最佳答案

问题是该文件没有被复制到您的应用程序包中。要修复它:

  • 点击您的项目
  • 点击您的目标
  • 选择构建阶段
  • 扩展复制捆绑资源
  • 点击“+”并选择您的文件。

关于ios - Bundle.main.path(forResource :ofType:inDirectory:) returns nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41775563/

相关文章:

ios - 如何在 Apple Silicon ('M1' ) 上构建 Google Analytics SDK 使其在 Xcode Simulator 中运行?

swift - 这个语句在 swift 中相当于什么?

ios - 如何快速从数组中获取对象索引

ios - 使用pdf图像设置背景

macos - Mac 上是否预装了 freetype?

iphone - UIImage 字节顺序已更改

IOS 推送通知错误

ios - 使用 Watch 连接框架将数据从 iPhone 传输到 iWatch

linux - 从同步任务(launchdaemon)中卸载 LaunchAgent

swift - 访问非空变量时出现 EXC_BAD_ACCESS 异常