Bundle.main.path(forResource:ofType:inDirectory:) 返回 nil [英] Bundle.main.path(forResource:ofType:inDirectory:) returns nil

查看:20
本文介绍了Bundle.main.path(forResource:ofType:inDirectory:) 返回 nil的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

Try not to laugh or cry -- I'm just getting back into coding after 20 years out...

I've spent more than 4 hours looking at references and trying code snippets to get Bundle.main.path to open my text file so I can read in data for my app (my next step is to appropriately parse it).

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 ... 菜单项.

The result is: "newTest.txt not found." regardless of how I try to drag&drop the file into the project, create the file inside Xcode or use the File -> Add Files to ... menu item.

推荐答案

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

The issue is that the file isn't being copied to your app bundle. To fix it:

  • 点击您的项目
  • 点击你的目标
  • 选择构建阶段
  • 扩展复制包资源
  • 点击+"并选择您的文件.

这篇关于Bundle.main.path(forResource:ofType:inDirectory:) 返回 nil的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆