NSBundle.mainBundle()。pathForResource返回nil

时间:2015-07-06 04:57:49

标签: ios objective-c swift nsbundle

我正在尝试为Swift编写一个简单的IO包装器。

为了测试这个,我的项目根目录中有一个名为“Test.txt”的文件。

我已将此文件添加到Build Bundle Resources中的Build Phases,正如其他遇到此问题的人所建议的那样。

Build Bundle Resources

我实现了一个非常简单的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”

为什么呢? :)

7 个答案:

答案 0 :(得分:58)

请勿在名称参数中加入.txt,并将其作为扩展程序参数传递。
来自documentation

  

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

Swift3

let bundle = Bundle.main
let path = bundle.path(forResource: "Test", ofType: "txt")

Swift1&amp; Swift2

let bundle = NSBundle.mainBundle()
let path = self.bundle.pathForResource("Test", ofType: "txt")

目标C

NSBundle* bundle = [NSBundle mainBundle];
NSString* path = [bundle pathForResource:@"Test" ofType:@"txt"];

答案 1 :(得分:18)

在swift 3.0中,用

[segmentControl setSelectedSegmentIndex:0];

答案 2 :(得分:13)

替换

 let path = self.bundle.pathForResource("Test.txt", ofType: "txt") 

let path = NSBundle.mainBundle().pathForResource("Test", ofType: "txt") 

答案 3 :(得分:7)

替换

let path = self.bundle.pathForResource("Test.txt", ofType: "txt") 

let path = self.bundle.pathForResource("Test", ofType: "txt") 

答案 4 :(得分:1)

对于那些试图在单元测试中访问资源的人,我遇到了一个问题,即在主要包中找不到资源而我的解决方案是在所有包中搜索路径,这样我就不会必须指定一个包标识符,其中fileName是一个传递给函数的字符串,当然类型可以是你想要的任何东西。

NSString *path;

for (NSBundle *bundle in [NSBundle allBundles]) {
    path = [bundle pathForResource:fileName ofType:@"json"];
    if (path) {
        break;  // Here is your path.
    }
}

答案 5 :(得分:0)

ofType 参数附加到资源名称,因此请替换此行:

 let path = self.bundle.pathForResource("Test.txt", ofType: "txt") 

这样的事情:

 let path = self.bundle.pathForResource("Test", ofType: "txt") 

构建捆绑资源也需要检查。

答案 6 :(得分:0)

NSBundle.mainBundle()。pathForResource返回nil的另一个原因是文件未正确添加到目标。当您将文件拖放到捆绑包中时,请确保选中“添加到目标”复选框和“复制项目(如果需要)”复选框。

相关问题