ios - Xcode 10 : Load the same . 项目目标和单元测试目标中的xml文件

标签 ios swift xcode macos unit-testing

我尝试在项目目标和单元测试目标中加载相同的 .xml 文件。

好像是类似这个问题的问题:Xcode. Image resources added to a test target are not copied into the tests bundle

在项目目标中,这段代码片段运行良好。我只需将“xmlString.xml”文件添加到“复制文件”(参见图 1)。

func parseFile() {
   let stringPath = Bundle.main.path(forResource: "xmlString", ofType: "xml")
   let url = NSURL(fileURLWithPath: stringPath!)
   ...
}

Image1

如果我运行在单元测试目标中截取的代码,我会收到错误消息,因为找不到 .xml 文件。我尝试将 .xml 文件添加到“Copy Bundle Resources”,但没有成功(见图 2)。

image 2

让它工作的唯一方法是使用绝对路径

func parseFile() {
   let stringPath: String? = "/Users/.../Documents/Git/.../.../.../.../xmlString.xml"
   let url = NSURL(fileURLWithPath: stringPath!)
   ...
}

有没有办法使用 Bundle.main.path(forResource: "xmlString", ofType: "xml") 函数代替绝对路径?

提前致谢!

最佳答案

您可以像这样为您的项目获取包:

let projectBundle = Bundle(for: AnyClassInMyProject.self)

AnyClassInMyProject 替换为项目中实际类的名称。

然后您可以像这样获取 .xml 文件的路径:

let stringPath = projectBundle.path(forResource: "xmlString", ofType: "xml")

关于ios - Xcode 10 : Load the same . 项目目标和单元测试目标中的xml文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53239259/

相关文章:

ios - JSON 到核心数据 SQLITE 错误

ios - 单击按钮编辑 UITextView

ios - Swift:获取 CoreData 作为数组

ios - 切换选项卡后 UIViewcontroller 消失 UITabBarController

swift - 如何从类数组中获取不同的值?

Xcode 无法启动,卡在 'Verifying "Xcode“...”

ios - 获取 Assets 目录文件夹中所有图像的数组

ios - 如何检查和取消选中ios中的按钮

iphone - 按 NSDate 对字典数组进行排序

objective-c - 在与主类分开的 .m 文件中实现 objc 协议(protocol)方法?