Swift - 如何获取文件夹内的文件路径 [英] Swift - How do I get the file path inside a folder

查看:60
本文介绍了Swift - 如何获取文件夹内的文件路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个文件夹中有一组音频文件.当文件放置在主包中时,我可以访问该文件,但如果将文件移动到文件夹内,我将无法访问这些文件.

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.

错误:

致命错误:解包可选值时意外发现 nil

fatal error: unexpectedly found nil while unwrapping an Optional value

推荐答案

首先确保当您将文件夹 audioFiles 拖到您的项目时,如果需要检查复制项目并选择创建文件夹引用.如果您的项目,请确保它显示一个蓝色文件夹.

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.

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:, subdirectory:)

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 - 如何获取文件夹内的文件路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆