【发布时间】:2015-09-23 03:19:26
【问题描述】:
我正在尝试为 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”
为什么? :)
【问题讨论】:
-
let path = self.bundle.pathForResource("Test.txt", ofType: "txt"),表示寻找资源Text.txt.txt...参数中不需要txt之一。
标签: ios objective-c swift nsbundle