ios Swift 3:如何获取保存在 Documents 文件夹中的文件路径
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40598942/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Swift 3 : How to get path of file saved in Documents folder
提问by Marin
path = Bundle.main.path(forResource: "Owl.jpg", ofType: "jpg")
returns nil, however, using NSHomeDirectory()
I'm able to verify that is under Documents/
folder.
返回零,但是,使用NSHomeDirectory()
我能够验证它在Documents/
文件夹下。
回答by matt
First, separate name and extension:
首先,分开名称和扩展名:
Bundle.main.path(forResource: "Owl", ofType: "jpg")
Second, separate (mentally) your bundle and the Documents folder. They are two completely different things. If this file is the Documents folder, it absolutely is not in your main bundle! You probably want something like this:
其次,(在心理上)将您的包和 Documents 文件夹分开。它们是完全不同的两种东西。如果此文件是 Documents 文件夹,则它绝对不在您的主包中!你可能想要这样的东西:
let fm = FileManager.default
let docsurl = try! fm.url(for:.documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
let myurl = docsurl.appendingPathComponent("Owl.jpg")
Third, if Owl is an image asset in the asset catalog, then say
第三,如果猫头鹰是资产目录中的图像资产,那么说
let im = UIImage(named:"Owl") // or whatever its name is
回答by Atlas_Gondal
Tested on: xCode 8.3.2& Swift 3.1
测试:xCode 8.3.2& Swift 3.1
First drag your file (JPG, MP3, ZIP) inside your project folder and make sure Copy items if neededis checked and project/app is selected in Add to targets
首先将您的文件(JPG、MP3、ZIP)拖入您的项目文件夹中,并确保选中需要时复制项目并在添加到目标中选择项目/应用程序
Inside relevant ViewController
在相关的ViewController里面
let fileName = "fileName"
let fileType = "fileType"
if let filePath = Bundle.main.path(forResource: fileName, ofType: fileType) {
print(filePath)
}
If you need to get the file URL you can use NSBundle method
如果需要获取文件 URL,可以使用 NSBundle 方法
if let fileURL = Bundle.main.url(forResource: fileName, withExtension: fileType) {
print(fileURL)
}
Also NSBundle method pathForResource has an initializer that you can specify in which directory your files are located like:
NSBundle 方法 pathForResource 也有一个初始值设定项,您可以指定文件所在的目录,例如:
if let filePath = Bundle.main.path(forResource: fileName, ofType: fileType, inDirectory: "filesSubDirectory") {
print(filePath)
}
And for getting file URL:
获取文件 URL:
if let fileURL = Bundle.main.url(forResource: fileName, withExtension: fileType, subdirectory: "filesSubDirectory") {
print(fileURL)
}