我正在尝试测试一些东西,并且需要访问与测试类位于同一目录中的文件(实际上在子目录中)。我正在尝试这样做:
let fileURL = testBundle.URLForResource("MasterCalendar", withExtension: "ics", subdirectory: "Calendars")
我也这样试过:
let fileURL = testBundle.URLForResource("MasterCalendar", withExtension: "ics")
我的类(class)叫做 ParserTest。我试图访问的文件位于如下所示:
我试图获取文件路径:
if let filePath = NSBundle.mainBundle().pathForResource("MasterCalendar", ofType: "ics", inDirectory: "Calendars") {
print("PATH: ", filePath)
}
我试图删除 inDirectory,并放入“CallInTests/Calendar”。没有任何效果。 文件本身被添加到目标中以进行测试:
无论我做什么,fileURL 总是返回 nil。
最佳答案
我不太清楚你的 testBundle
是如何定义的,但这对我有用:
let bundle = Bundle(for: YourClassHere.self)
所以在你的情况下会是:
let bundle = Bundle(for: ParserTest.self)
然后你可以像这样使用:
if let path = bundle.path(forResource: "MasterCalendar", ofType: "ics") {
//magic goes here
}
swift 2.3 版本
let bundle = NSBundle(forClass: ParserTest.self)
if let path = bundle.pathForResource("MasterCalendar", ofType: "ics") {
//magic still goes here :)
}
希望对你有帮助。
关于ios - URLForResource() 总是返回 nil,swift 2.3,iOS10,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39895963/