Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get path to a subfolder in main bundle?

I have a project which I am migrating from Obj-C to Swift 3.0 (and I am quite a noob in Swift).

How do I translate this line?

NSString *folder = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"myfolder"];

I managed to get resource path:

let resoursePath = Bundle.main.resoursePath;

But how do I get path to a subfolder named "myfolder"? I need to get a path the subfolder, not path to the files inside it.

like image 325
Nick Avatar asked Nov 19 '16 12:11

Nick


3 Answers

In Swift-3 make URL, and call appendingPathComponent:

let resourcePath = Bundle.main.resourcePath
let subdir = URL(fileURLWithPath:resourcePath!).appendingPathComponent("sub").path

or simply

let subdir = Bundle.main.resourceURL!.appendingPathComponent("sub").path

(thanks, Martin R!)

See this Q&A on information on stringByAppendingPathComponent method in Swift.

like image 125
Sergey Kalinichenko Avatar answered Oct 29 '22 21:10

Sergey Kalinichenko


You can use this method to get listing of the bundle subdirectory and get resources only of the specific type:

Bundle.main.paths(forResourcesOfType: type, inDirectory: folder)
like image 26
Denis Rodin Avatar answered Oct 29 '22 22:10

Denis Rodin


You can do something like this:

let folderURL = resourceURL(to: "myfolder")

func resourceURL(to path: String) -> URL? {
    return URL(string: path, relativeTo: Bundle.main.resourceURL)
}
like image 34
jangelsb Avatar answered Oct 29 '22 21:10

jangelsb