14

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.

Nirav D
  • 71,513
  • 12
  • 161
  • 183
Nick
  • 3,205
  • 9
  • 57
  • 108

4 Answers4

19

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.

Community
  • 1
  • 1
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
2

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)
}
jangelsb
  • 171
  • 1
  • 5
1

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)
Denis Rodin
  • 319
  • 1
  • 7
0

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")
Andrew Kingdom
  • 188
  • 1
  • 9