ios - 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!)
...
}
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).
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!
解决方案
您可以像这样为您的项目获取捆绑包:
let projectBundle = Bundle(for: AnyClassInMyProject.self)
替换AnyClassInMyProject
为项目中实际类的名称。
然后,您可以像这样获取 .xml 文件的路径:
let stringPath = projectBundle.path(forResource: "xmlString", ofType: "xml")
推荐阅读
- python - 从具有 NA 值的日期获取年份和月份作为字符串
- java - GET 请求的参数被放入 URL 的查询字符串中。在 POST 请求中,它们位于请求正文中,那么 URL 是什么样的?
- ios - 在 UICollectionView 中加载第一个单元格之前获取 UICollectionViewCell
- java - 西蒙说按下按钮后按钮颜色不会恢复正常
- javascript - jQuery UI datepicker 和对话框未定义的第一次点击
- nginx - Nginx 上的 Modsecurity modsecurity.conf-recommended Source Not Found
- mysql - phpmyadmin mysql docker 简单链接
- ecmascript-6 - es6 导入:命名导入的变量
- javascript - 将路径数组转换为唯一路径数组
- php - 根据列值对 JSON API 进行分类