Pascal
Pascal

Reputation: 1093

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!

Upvotes: 0

Views: 377

Answers (1)

Mike Taverne
Mike Taverne

Reputation: 9352

You can get the bundle for your project like this:

let projectBundle = Bundle(for: AnyClassInMyProject.self)

where you replace AnyClassInMyProject with the name of an actual class in your project.

You can then get the path to your .xml file like this:

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

Upvotes: 1

Related Questions