问题
I am trying to read a file from my bundle. I know this has been asked before but I have read the other SO solutions and not of them seem to be of my situation.
I have an XML file. I can see it in the project navigator:
and I can also check that it is included in the bundle by going to Project/Build Phases/Copy Bundle Resource
I've tried to get its path using the file manager with no luck, using inDirectory and not using inDirectory:
let filePath = Bundle.main.path(forResource: "config", ofType: "xml", inDirectory:"Resources")
I'm kind of at a loss as to what to try next.
Edit:
I got it to work but this seems to be way more code than I should need.
let arrFiles = getAllFiles()
let fileName = strFileName + "." + strFileExtension
for thisObj in arrFiles {
if thisObj == "config.xml" {
let filePath = Bundle.main.path(forResource: thisObj, ofType: nil)
print(filePath)
}
}
回答1:
Try this code:
if let filePath = Bundle.main.url(forResource: "config.xml", withExtension: nil, subdirectory: "/Resources") {
/// Do something with the filePath
}
来源:https://stackoverflow.com/questions/51875058/bundle-main-pathforresource-always-returns-nil-when-looking-for-xml-file