Nick
Nick

Reputation: 3435

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.

Upvotes: 15

Views: 20755

Answers (4)

Andrew Kingdom
Andrew Kingdom

Reputation: 403

Swift 5.0

Swift 5:

Caveat: Assumes that your folder is actually in the bundle; (that you added the folder to the project via 'Add Folder Reference', not by the 'Add Groups' option).

bundle.main.path(forResource: "myfolder", ofType: nil)

Objective-C: (your example)

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

Other Swift ways:

As a URL (Apple's preferred method, the :URL? is only included here to clarify that this does not produce a string):

let folderURL:URL? = Bundle.main.url(forResource: "myfolder", withExtension: nil)

Appending as a string:

let folder = Bundle.main.resourcePath?.appending("/myfolder")
// or
let y = Bundle.main.resourcePath?.appending("/").appending("myfolder")

The following literal translation fails, as appendingPathComponent is no longer available in the Swift String type which is slightly different from NSString:

let folder = Bundle.main.resourcePath?.appendingPathComponent("myfolder")

Upvotes: 1

jangelsb
jangelsb

Reputation: 191

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

Upvotes: 2

Denis Rodin
Denis Rodin

Reputation: 319

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)

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726639

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.

Upvotes: 19

Related Questions