Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - How do I get the file path inside a folder

Tags:

I have a set of audio files inside a folder. I am able to access the file when the file is placed at main bundle, but if the files are moved inside the folder I am not able to access the files.

Code:

let audioFileName:String = "audioFiles/" + String(index) let audioFile = NSBundle.mainBundle().pathForResource(audioFileName, ofType: "mp3")! 

I have an audio file inside the folder audioFiles and I would want to get its path.

Error:

fatal error: unexpectedly found nil while unwrapping an Optional value

like image 924
Rahul Krishna Avatar asked Dec 31 '15 16:12

Rahul Krishna


People also ask

How do I open a file path in Swift?

open("path"); while var line = fh. readline() { ... }; fh. close() . @BryanChen Yep, that's my hope.

What is the path of a folder?

A path is a slash-separated list of directory names followed by either a directory name or a file name. A directory is the same as a folder.


1 Answers

First make sure when you drag your folder audioFiles to your project to check copy items if needed and select create folder references. Make sure it shows a blue folder if your project.

enter image description here

enter image description here

Also NSBundle method pathForResource has an initialiser that you can specify in which directory your files are located:

let audioFileName = "audioName"   if let audioFilePath = Bundle.main.path(forResource: audioFileName, ofType: "mp3", inDirectory: "audioFiles") {     print(audioFilePath) } 

If you would like to get that file URL you can use NSBundle method URLForResource(withExtension:, subdirectory:)

if let audioFileURL = Bundle.main.url(forResource: audioFileName, withExtension: "mp3", subdirectory: "audioFiles") {     print(audioFileURL) } 
like image 147
Leo Dabus Avatar answered Oct 07 '22 01:10

Leo Dabus