我正在尝试为Swift编写一个简单的IO包装器。
为了测试这个,我在项目根目录中有一个名为“Test.txt”的文件。
我已将此文件添加到Build Bundle Resources中的Build Phases,正如遇到此问题的所有其他人所建议的那样。
我已经实现了一个非常简单的File类,其中包含一个读取函数,目的是输出文件的内容。
class File2{
let resourceName: String
let type: String
let bundle = NSBundle.mainBundle()
init(resourceName: String, type: String = "txt"){
self.resourceName = resourceName
self.type = type
println(self.bundle)
}
func read(){
let path = self.bundle.pathForResource("Test.txt", ofType: "txt") //Hard coded these in just to make sure Strings contained no whitespace
println(path) //This returns nil...why?
var error:NSError?
//print(String(contentsOfFile:path!, encoding:NSUTF8StringEncoding, error: &error)!)
//return String(contentsOfFile:path!, encoding:NSUTF8StringEncoding, error: &error)!
}
}
当我打印捆绑包的内容时,我得到一个URI到我的文件系统上的特定位置,我假设它是模拟器中应用程序的虚拟位置。导航到它显示它确实包含我的“Test.txt”文件。
现在,我想要做的就是获取该文件的路径。
我这样做是通过调用:self.bundle.pathForResource("Test.txt", ofType: "txt")
这返回“nil”
为什么? :)
不要在name参数中包含.txt
,将其作为扩展参数传递。
来自documentation:
延期 要查找的文件的文件扩展名。 如果指定空字符串或nil,则假定扩展名不存在,并且该文件是遇到的与名称完全匹配的第一个文件。
let bundle = Bundle.main
let path = bundle.path(forResource: "Test", ofType: "txt")
let bundle = NSBundle.mainBundle()
let path = self.bundle.pathForResource("Test", ofType: "txt")
NSBundle* bundle = [NSBundle mainBundle];
NSString* path = [bundle pathForResource:@"Test" ofType:@"txt"];
在swift 3.0中,写一下
let path = Bundle.main.path(forResource: "Test", ofType: "txt")
替换你的
let path = self.bundle.pathForResource("Test.txt", ofType: "txt")
同
let path = NSBundle.mainBundle().pathForResource("Test", ofType: "txt")
更换
let path = self.bundle.pathForResource("Test.txt", ofType: "txt")
同
let path = self.bundle.pathForResource("Test", ofType: "txt")
对于那些试图在单元测试中访问资源的人,我遇到了一个问题,即在主包中找不到资源,我的解决方案是在所有包中搜索路径,这样我就不必指定了一个包标识符,其中fileName
是一个传递给函数的字符串,当然类型可以是你想要的任何东西。
NSString *path;
for (NSBundle *bundle in [NSBundle allBundles]) {
path = [bundle pathForResource:fileName ofType:@"json"];
if (path) {
break; // Here is your path.
}
}
ofType参数附加到资源名称,因此替换此行:
let path = self.bundle.pathForResource("Test.txt", ofType: "txt")
这样的事情:
let path = self.bundle.pathForResource("Test", ofType: "txt")
Build Bundle Resources也需要检查。
NSBundle.mainBundle()。pathForResource返回nil的另一个原因是文件未正确添加到目标。当您将文件拖放到捆绑包中时,请确保选中“添加到目标”复选框和“复制项目(如果需要)”复选框。