简体   繁体   English

URLForResource() 总是返回 nil,swift 2.3,iOS10

[英]URLForResource() returns always nil, swift 2.3, iOS10

I am trying to test something, and need access to the file which is in the same directory as the test class (in fact in sub-directory).我正在尝试测试某些内容,并且需要访问与测试类位于同一目录中的文件(实际上在子目录中)。 I am trying to do it like this:我正在尝试这样做:

let fileURL = testBundle.URLForResource("MasterCalendar", withExtension: "ics", subdirectory: "Calendars")

I also tried it like this:我也这样试过:

let fileURL = testBundle.URLForResource("MasterCalendar", withExtension: "ics")

My class is called ParserTest.我的课程叫做 ParserTest。 The file I am trying to access is located as shown:我试图访问的文件位于如下所示: 在此处输入图片说明

I tried to get the file path:我试图获取文件路径:

 if let filePath = NSBundle.mainBundle().pathForResource("MasterCalendar", ofType: "ics", inDirectory: "Calendars") {
        print("PATH: ", filePath)
    }

I tried to remove inDirectory, and put also "CallInTests/Calendar".我试图删除 inDirectory,并放入“CallInTests/Calendar”。 Nothing worked.没有任何效果。 The file itself is added in the Target for tests:文件本身被添加到测试目标中:

在此处输入图片说明

AND for the project:并且对于该项目: 在此处输入图片说明

Regardless of what I do, the fileURL returns always nil.不管我做什么,fileURL 总是返回 nil。

It is not quite clear to me how your testBundle is defined, but this works for me:我不太清楚您的testBundle是如何定义的,但这对我testBundle

let bundle = Bundle(for: YourClassHere.self)

So in your case that would be:所以在你的情况下,这将是:

let bundle = Bundle(for: ParserTest.self)

Which you can then use like so:然后你可以像这样使用:

if let path = bundle.path(forResource: "MasterCalendar", ofType: "ics") {
  //magic goes here
}

Swift 2.3 version斯威夫特 2.3 版本

let bundle = NSBundle(forClass: ParserTest.self)

if let path = bundle.pathForResource("MasterCalendar", ofType: "ics") {
   //magic still goes here :)
}

Hope that helps you.希望能帮到你。

try the following way :尝试以下方式:

let testBundle = NSBundle(forClass: self.dynamicType)
let fileURL = testBundle.URLForResource("MasterCalendar", withExtension: "ics")
XCTAssertNotNil(fileURL)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM