ios Bundle.main.path(forResource:ofType:inDirectory:) 返回 nil

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41775563/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 11:05:07  来源:igfitidea点击:

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

iosswiftmacosfileswift3

提问by Zakarius Jay Poggenpohl

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).

尽量不要笑或哭——我刚在 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.")
}

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.

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

回答by Denis Hennessy

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

问题是该文件没有被复制到您的应用程序包中。要解决这个问题:

  • Click your project
  • Click your target
  • Select Build Phases
  • Expand Copy Bundle Resources
  • Click '+' and select your file.
  • 单击您的项目
  • 点击你的目标
  • 选择构建阶段
  • 展开复制包资源
  • 单击“+”并选择您的文件。

回答by shallowThought

Double check the Optionsin the add filesmenu when adding the file. The target in Add to targetsmust be ticked to add it to the bundle:

仔细检查Optionsadd files添加文件时菜单。Add to targets必须勾选目标 in才能将其添加到包中:

In case you are actually in another bundle (test for instance), use:

如果您实际上在另一个包中(例如测试),请使用:

guard let fileURL = Bundle(for: type(of: self)).url(forResource: fileName withExtension:"txt") else {
        fatalError("File not found")
}

回答by Kelvin Fok

Click on your file on your navigation panel and open the Right Panel/ Property Inspector.

单击导航面板上的文件并打开右侧面板/属性检查器。

enter image description here

在此处输入图片说明

Ensure that you add to target membership

确保您添加到目标成员资格

回答by Himanshu Moradiya

Swift 3.0

斯威夫特 3.0

let fileNmae = "demo"

let path = Bundle.main.path(forResource: fileNmae, ofType: "txt")
    do {
        let content = try String(contentsOfFile:path!, encoding: String.Encoding.utf8)
        print(content)
    } catch {
        print("nil")
    }

SWift 2.0

斯威夫特 2.0

do{
      if let path = NSBundle.mainBundle().pathForResource("YOURTXTFILENAME", ofType: "txt"){
             let data = try String(contentsOfFile:path, encoding: NSUTF8StringEncoding)
             let myStrings = data.componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet())
              print(myStrings)
       }
  } catch let err as NSError {
            //do sth with Error
            print(err)
  }

Output :

输出 :

Hello Hems
Good Morning
I m here for you dude.
Happy Coding.

回答by Montmons

Ah, so just found myself dealing with the exact same problem as the OP.

啊,所以刚刚发现自己正在处理与 OP 完全相同的问题。

The problem is that the solutions given hereand heredo not work when the code is being executed in a playground, since the Optionsmenu of add fileslooks different for it does not show the Add to targetsfield:

问题是当代码在操场上执行时,这里这里给出的解决方案不起作用,因为它的Options菜单add files看起来不同,因为它没有显示Add to targets字段:

enter image description here

在此处输入图片说明

When inside a .playgroundfile, instead press the Hide or show the Navigatorbutton on the top-right of your Xcode window (visual impression)--> enter image description here

.playground文件中时,请按Hide or show the NavigatorXcode 窗口右上角的按钮(视觉印象)-->在此处输入图片说明

Then, once the Navigator folds open on the left-side of the Xcode window, simply drag & drop your file to the Resourcesdirectory of your playground.

然后,一旦导航器在 Xcode 窗口的左侧折叠打开,只需将您的文件拖放到Resources您的 Playground 目录中即可。

If your setup looks anything like the following you should be ok:

如果您的设置如下所示,您应该没问题:

enter image description here

在此处输入图片说明

回答by peacetype

Same problem, slightly different situation & solution. I'm following a tutorial that said to use the following code:

同样的问题,情况和解决方案略有不同。我正在关注一个教程,该教程说使用以下代码:

    // Start the background music:
    if let musicPath = Bundle.main.path(forResource:
        "Sound/BackgroundMusic.m4a", ofType: nil) {
        print("SHOULD HEAR MUSIC NOW")
        let url = URL(fileURLWithPath: musicPath)

        do {
            musicPlayer = try AVAudioPlayer(contentsOf: url)
            musicPlayer.numberOfLoops = -1
            musicPlayer.prepareToPlay()
            musicPlayer.play()
        }
        catch { print("Couldn't load music file") }
    }
}

I had the same issue as others but none of the solutions fixed the issue. After experimenting, all I did was remove Soundfrom the path in the following call and everything worked:

我和其他人有同样的问题,但没有一个解决方案解决了这个问题。经过试验,我所做的就是在以下调用中从路径中删除Sound并且一切正常:

Bundle.main.path(forResource: "BackgroundMusic.m4a", ofType: nil)

It would seem that the tutorial was in error by telling me to include Soundin the path.

通过告诉我在路径中包含Sound似乎教程是错误的。

回答by Ryan R

I added file.txtto my project and it was automatically added to the Copy Bundle Filesof my project. For me, I had to remove the extension from the forResourceand it worked.

我添加file.txt到我的项目中,它会自动添加到Copy Bundle Files我的项目中。对我来说,我必须从 中删除扩展名forResource并且它起作用了。

let path = Bundle.main.path(forResource: "file", ofType: "txt") // not forResource: "file.txt"

回答by Arkadiusz Turlewicz

This was helpful for me: xcode - copy a folder structure into my app bundle

这对我很有帮助:xcode - 将文件夹结构复制到我的应用程序包中

Mark "create folder references" option when you create assets in nested folders.

在嵌套文件夹中创建资产时,标记“创建文件夹引用”选项。

Then find path to the file like this:

然后像这样找到文件的路径:

let path = Bundle(for: type(of : self)).path(forResource: "some_folder_a/some_folder_b/response.json", ofType: nil)

回答by rob mayoff

I think you don't want the inDirectory:method. Try this instead:

我想你不想要这个inDirectory:方法。试试这个:

if let filepath = Bundle.main.path(forResource: "newTest", ofType: "txt") {