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

Zak*_*ohl 64 macos file ios swift 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.")
}
Run Code Online (Sandbox Code Playgroud)

结果是:"找不到newTest.txt." 无论我如何尝试将文件拖放到项目中,在Xcode中创建文件或使用文件 - >添加文件到...菜单项.

Den*_*ssy 152

问题是该文件没有处理您的应用包.要解决这个问题:

  • 单击您的项目
  • 单击您的目标
  • 选择Build Phases
  • 展开Copy Bundle Resources
  • 点击"+"并选择您的文件.

  • 没有别的办法,这对我有用.为什么我放入Xcode的文件不会自动显示在"Copy Bundle Resources"下? (9认同)

sha*_*ght 25

仔细检查Optionsadd files添加文件时菜单.Add to targets必须勾选目标以将其添加到捆绑包中:

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

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


Kel*_*Fok 12

单击导航面板上的文件,然后打开右侧面板/属性检查器.

在此输入图像描述

确保添加到目标成员身份

  • 对于看到此内容的任何其他人,这对您和我来说都是解决方案,您必须在文件被新版本替换时执行此操作。 (2认同)

Ark*_*icz 6

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

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

然后找到文件的路径,如下所示:

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


ran*_*rol 6

这么简单的问题要花费多少时间,真是太疯狂了。

这里的一些答案对我有帮助,但我总是尝试:

Bundle.main.url(forResource: selectedTitle, withExtension: "mp3")
Run Code Online (Sandbox Code Playgroud)

出于某种原因,这不起作用,但获取路径并将其转换为 URL 之后可以工作:

let path = Bundle.main.path(forResource: selectedTitle, ofType: "mp3")
let url = URL(fileURLWithPath: path!)
Run Code Online (Sandbox Code Playgroud)


Joh*_*tts 6

答案很简单,不要使用 Assets.xcassets 来存储音频文件,而是将音频文件(即)BeTheFirstAudio.m4a(用 QuickTime 制作)直接添加到 PROJECT NAVIGATOR(圆圈、粉红色)文件列表中(照片 1)

在此输入图像描述

警告!从 Finder 窗口拖动音频文件后出现弹出窗口时,请务必选中“创建组”和“添加到目标”复选框。

在此输入图像描述

之后,您的代码应该可以播放音频(包括 QuickTime 的 .m4a 扩展名)

 import AVFoundation

 class AudioPlayer: NSObject {


     private var audioPlayer: AVAudioPlayer!

     override init() {
         super.init()
    
         // get URL for the default audio
         let audioURL = Bundle.main.url(forResource: "BeTheFirstAudio", withExtension: "m4a")

         audioPlayer = try! AVAudioPlayer(contentsOf: audioURL!)
     }
Run Code Online (Sandbox Code Playgroud)

苹果工程师应该感到羞愧,这个问题甚至是 StackOverflow 中的一个问题;开发人员应该能够将音频文件添加到 Assets.xcassets 中,并且 Bundle.main.url 应该能够找到它。事实上,这个简单的概念很困难,可能已经花费了开发人员大量的时间。注意@苹果


Him*_*iya 5

Swift 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")
    }
Run Code Online (Sandbox Code Playgroud)

SWift 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)
  }
Run Code Online (Sandbox Code Playgroud)

输出:

Hello Hems
Good Morning
I m here for you dude.
Happy Coding.
Run Code Online (Sandbox Code Playgroud)


rob*_*off 0

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

if let filepath = Bundle.main.path(forResource: "newTest", ofType: "txt") {
Run Code Online (Sandbox Code Playgroud)