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

查看:833
本文介绍了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中创建文件或使用文件"->将文件添加到..."菜单项.

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天全站免登陆