我试图为Swift编写一个简单的IO包装器。
为了测试这一点,我在我的项目根目录中有一个名为"Test.txt“的文件。
我添加了这个文件以在Bundle参考资料中构建阶段,正如其他有此问题的人所建议的那样。
我实现了一个非常简单的file类,其中包含一个read函数,目的是输出文件的内容。
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")
返回“零”。
为什么?:)
发布于 2015-07-05 21:02:24
不要将.txt
包含在name参数中,将其作为扩展参数传递。
扩展 要定位的文件的文件扩展名。 如果指定空字符串或零,则假定扩展名不存在,并且该文件是遇到的第一个与名称完全匹配的文件。
Swift3
let bundle = Bundle.main
let path = bundle.path(forResource: "Test", ofType: "txt")
Swift1 & Swift2
let bundle = NSBundle.mainBundle()
let path = self.bundle.pathForResource("Test", ofType: "txt")
Objective-C
NSBundle* bundle = [NSBundle mainBundle];
NSString* path = [bundle pathForResource:@"Test" ofType:@"txt"];
发布于 2016-09-21 05:49:06
在斯威夫特3.0中,用
let path = Bundle.main.path(forResource: "Test", ofType: "txt")
发布于 2015-07-05 21:13:10
替换你的
let path = self.bundle.pathForResource("Test.txt", ofType: "txt")
使用
let path = NSBundle.mainBundle().pathForResource("Test", ofType: "txt")
https://stackoverflow.com/questions/31238031
复制