ios - Xcode - 将图像添加到测试中?

标签 ios xcode swift

我目前正在为 Swift 应用程序编写测试。在此期间我需要测试处理图像。我想添加一个示例图像进行测试。根据我的理解,这似乎是错误的,我应该能够直接将图像拖到 Xcode 的 ProductNameTests 目录中。这会将图像添加到测试目标。然后我尝试这样获取图像的路径:

let imagePath = NSBundle.mainBundle().pathForResource("example_image", ofType: "jpg")

不幸的是,这总是返回 nil。我究竟做错了什么?谢谢!

最佳答案

您的问题是,您在主包中搜索图像。因此,目前您访问的 mainBundle 中不存在您的图像,因为它在测试包中。

因此您需要访问另一个包。嵌套测试类的包。

为此,使用 bundleForClass 而不是 mainBundle:

//The Bundle for your current class
var bundle = NSBundle(forClass: self.dynamicType)
var path = bundle.pathForResource("example_image", ofType: "jpg")

如您所见,您为您的类加载了 NSBundle,您现在应该能够访问该图像。您还可以将图像添加到主要目标并再次使用 mainBundle

关于ios - Xcode - 将图像添加到测试中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28328478/

相关文章:

ios - View Controller 的一部分是静止的,一部分是水平滚动的

swift - 设计 Swift API 时的可选项

swift - 为 getRequestedUpdateDateWithHandler 构造日期 :

swift - 有没有一种方法可以有 float 区域,这样我们就可以在 Xcode 的多个屏幕上工作?

IOS 呈现 PageViewController

ios - AVPlayerItem 奇怪的缓冲区观察者

iOS 7 UINavigationBar Retina 图像大小

ios - 如何在左侧导航栏项目上添加圆形图像

iphone - 如何开始使用 airplay?

ios - iCloud:NSUbiquitousKeyValueStore 问题