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

标签 ios swift xcode

我正在尝试测试一些东西,并且需要访问与测试类位于同一目录中的文件(实际上在子目录中)。我正在尝试这样做:

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

我也这样试过:

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

我的类(class)叫做 ParserTest。我试图访问的文件位于如下所示: enter image description here

我试图获取文件路径:

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

我试图删除 inDirectory,并放入“CallInTests/Calendar”。没有任何效果。 文件本身被添加到目标中以进行测试:

enter image description here

并且对于项目: enter image description here

无论我做什么,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/

相关文章:

c++ - 如何在 Xcode 中链接动态库?

objective-c - -initWithContentsOfFile : for an NSMutableArray

ios - 保存到核心数据时使用谓词防止数组中的重复条目

ios - 扩张重点

ios - 在 viewDidLoad 之外更改 UIView 元素

xcode - 如何将 OpenSSL 添加到 Xcode 项目

ios - 触觉引擎 iPhone 冲击力更强

Swift 代码错误 : Value of type String has no member Int

ios - 当我们可以使用数组在 swift 中返回多个值时,为什么要使用元组

ios - UIButton Outlet 设置标题 Swift