NSBundle.mainBundle().pathForResource返回nil

Jam*_*inB 32 objective-c nsbundle ios swift

我正在尝试为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)!
    }
}
Run Code Online (Sandbox Code Playgroud)

当我打印捆绑包的内容时,我得到一个URI到我的文件系统上的特定位置,我假设它是模拟器中应用程序的虚拟位置.导航到它显示它确实包含我的"Test.txt"文件.

现在,我想要做的就是获取该文件的路径.

我这样做是通过调用: self.bundle.pathForResource("Test.txt", ofType: "txt")

这返回"nil"

为什么?:)

Swi*_*ect 61

不要.txtname参数中包含,将其作为扩展参数传递.
文档:

extension
要查找的文件的文件扩展名.
如果指定空字符串或nil,则假定扩展名不存在,并且该文件是遇到的与名称完全匹配的第一个文件.

Swift3

let bundle = Bundle.main
let path = bundle.path(forResource: "Test", ofType: "txt")
Run Code Online (Sandbox Code Playgroud)

Swift1和Swift2

let bundle = NSBundle.mainBundle()
let path = self.bundle.pathForResource("Test", ofType: "txt")
Run Code Online (Sandbox Code Playgroud)

Objective-C的

NSBundle* bundle = [NSBundle mainBundle];
NSString* path = [bundle pathForResource:@"Test" ofType:@"txt"];
Run Code Online (Sandbox Code Playgroud)


Vin*_*Vin 18

在swift 3.0中,写一下

let path = Bundle.main.path(forResource: "Test", ofType: "txt")
Run Code Online (Sandbox Code Playgroud)


Abh*_*rma 13

替换你的

 let path = self.bundle.pathForResource("Test.txt", ofType: "txt") 
Run Code Online (Sandbox Code Playgroud)

let path = NSBundle.mainBundle().pathForResource("Test", ofType: "txt") 
Run Code Online (Sandbox Code Playgroud)


Kir*_*ela 7

更换

let path = self.bundle.pathForResource("Test.txt", ofType: "txt") 
Run Code Online (Sandbox Code Playgroud)

let path = self.bundle.pathForResource("Test", ofType: "txt") 
Run Code Online (Sandbox Code Playgroud)