swiftfile

Get nil when looking for file in subdirectory of main bundle


I've copied a folder with index.html to the project.

When I try to get a path to the file inside a folder, I get nil.

let path = Bundle.main.path(forResource: "index", ofType: "html", inDirectory: "games/game1")

I also tried to use "/games/game1" string. Doesn't work though.

But when I move index.html to the root of my project and use

let path = Bundle.main.path(forResource: "index", ofType: "html")

I get a correct path.

So my question is how do I get the path of index.html inside a subfolder?


Solution

  • The solution is to use

    Bundle.main.url(forResource: "index", withExtension: "html", subdirectory: "games/game1")
    

    I don't know why, but it doesn't work if we get a path, then construct an URL from it.

    Note: You must

    1. Copy items if needed
    2. Create folder references (not "Create groups")
    3. Add to targets