问题描述
我在文件夹中有一组音频文件。我可以在文件放在主捆绑包时访问该文件,但如果文件在文件夹内移动,我将无法访问这些文件。
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.
代码:
let audioFileName:String = "audioFiles/" + String(index)
let audioFile = NSBundle.mainBundle().pathForResource(audioFileName, ofType: "mp3")!
我在audioFiles文件夹中有一个音频文件,我希望得到它的路径。
I have an audio file inside the folder audioFiles and I would want to get its path.
错误:
推荐答案
首先确保将文件夹audioFiles拖到项目中以选择创建文件夹引用,它应该显示一个蓝色文件夹。
First make sure when you drag your folder audioFiles to your project to select create folder references and it should show a blue folder.
NSBundle方法pathForResource还有一个初始化程序,您可以在其中指定文件所在的目录:
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)
}
如果您想获取该文件URL,可以使用NSBundle方法URLForResource(withExtension:,子目录:)
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)
}
这篇关于Swift - 如何获取文件夹中的文件路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!