Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get nil when looking for file in subdirectory of main bundle

Tags:

file

swift

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?

like image 926
Eugene Karambirov Avatar asked Aug 21 '18 19:08

Eugene Karambirov


2 Answers

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
like image 111
Eugene Karambirov Avatar answered Nov 15 '22 20:11

Eugene Karambirov


Alternatively, adding to Eugene's answer,

Swift 5:

Bundle.main.url(forResource: "index", withExtension: "html", inDirectory: "games/game1")
like image 23
Mumtaz Hussain Avatar answered Nov 15 '22 20:11

Mumtaz Hussain