PruitIgoe
PruitIgoe

Reputation: 6384

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

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:

enter image description here

and I can also check that it is included in the bundle by going to Project/Build Phases/Copy Bundle Resource

enter image description here

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)
            }

        }

Upvotes: 5

Views: 8492

Answers (1)

Mike Manzo
Mike Manzo

Reputation: 168

Try this code:

if let filePath = Bundle.main.url(forResource: "config.xml", withExtension: nil, subdirectory: "/Resources") {

   /// Do something with the filePath

}

Upvotes: 5

Related Questions