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

尽量不要大笑或者哭泣 – 我只是在20年之后才开始重新编码。

我花了超过4个小时看引用和尝试代码片断来获取Bundle.main.path打开我的文本文件,所以我可以读取我的应用程序的数据(我的下一步是适当地parsing它)。

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”。 不pipe我如何将文件拖放到项目中,在Xcode中创build文件或使用文件 – >添加文件到…菜单项。

问题是该文件没有应对你的应用程序包。 要解决这个问题:

  • 点击你的项目
  • 点击你的目标
  • select构build阶段
  • 展开复制包资源
  • 点击“+”并select您的文件。

add files时,请双击add files菜单中的OptionsAdd to targets必须勾选以将其添加到软件包中:

如果你真的在另一个捆绑(例如testing),使用:

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

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") } 

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

输出:

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

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

问题是,在代码在操场上执行时, 这里和这里给出的解决scheme不起作用,因为add files的“ Options菜单看起来不同,因此不会显示“ Add to targets字段:

在这里输入图像说明

当在.playground文件中时,改为按下Xcode窗口右上angular的Hide or show the Navigatorbutton(视觉印象) – > 在这里输入图像说明

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

如果你的设置看起来像下面这样你应该可以:

在这里输入图像说明

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

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

同样的问题,情况和解决scheme略有不同。 我正在遵循一个教程,说使用下面的代码:

  // 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") } } } 

我和其他人有同样的问题,但没有一个解决scheme解决了这个问题。 经过试验,我所做的只是在下面的调用中删除path中的声音 ,一切正常:

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

看起来,教程是错误的告诉我包括声音的path。