[英]Read file in Xcode project with Swift
I made a method to read a file from the temporary folder. 我做了一个从临时文件夹中读取文件的方法。 I use the following lines to get the document's path:
我使用以下行来获取文档的路径:
path = NSTemporaryDirectory().stringByAppendingPathComponent(folder)
path = path.stringByAppendingPathComponent(fileName + "." + fileType)
And it works great. 而且效果很好。 My question is: how do I get the path for a file located in the main folders of the Xcode project?
我的问题是:如何获取位于Xcode项目主文件夹中的文件的路径? They are two text files that I drag and drop from a folder to the Xcode project.
它们是我从文件夹拖放到Xcode项目的两个文本文件。 I selected the option "copy files if needed" when dropping the files.
删除文件时,我选择了“在需要时复制文件”选项。 Thanks!
谢谢!
What you are looking for is app's main bundle. 您正在寻找的是应用程序的主要包。 You get a path of a file in it like this:
你得到一个文件的路径,如下所示:
if let path = NSBundle.mainBundle().pathForResource(fileName, ofType:fileType) {
// use path
}
Keep in mind this folder is read-only so you will need to copy the files to temp or documents folders if you want to make changes. 请记住,此文件夹是只读的,因此如果要进行更改,则需要将文件复制到temp或文件夹。
Update the Swift 3.1 - Thanks @Filip Radelic 更新Swift 3.1 - 谢谢@Filip Radelic
if let path = Bundle.main.path(forResource: fileName, ofType: fileType) {
// use path
print(path)
}
Swift 4 斯威夫特4
if let path = Bundle.main.path(forResource: "imagename.png", ofType: nil) {
print("[check] FILE AVAILABLE \(path)")
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.