首页 > 解决方案 > Xcode 10: Load the same .xml file in project target and unit test target

问题描述

I try to load the same .xml file in project target and unit test target.

It seems to be a similar problem like this question: Xcode. Image resources added to a test target are not copied into the tests bundle

In project target, this code snipped worked fine. I just have to add the "xmlString.xml" file to "Copy Files" (see image 1).

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

Image1

If I run the code snipped in unit test target, I get an error because the .xml file can not be found. I tried to add the .xml file to the "Copy Bundle Resources" without any success (see image 2).

image 2

The only way to get it working is to use the absolute path

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

Is there a way to use the Bundle.main.path(forResource: "xmlString", ofType: "xml") function instead of the absolute path?

Thanks in advance!

标签: iosswiftxcodemacosunit-testing

解决方案


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

let projectBundle = Bundle(for: AnyClassInMyProject.self)

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

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

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

推荐阅读