Bundle.main.path(forResource… always returns nil when looking for xml file

有些话、适合烂在心里 提交于 2021-02-10 06:14:20

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!