Ondrej Ondrej - 1 year ago 576
Swift Question

How do I load a custom bundle in Swift 3

In Objective-C I was doing this:

NSString *path = [[NSBundle mainBundle] pathForResource:@"LUIImages" ofType:@"bundle"];
path = [[NSBundle bundleWithPath:path] pathForResource:_imageHash ofType:nil];

But I can't seem to find equivalent in swift 3

let bundlePath: String = Bundle.main.path(forResource: "LiveUI", ofType: "bundle")!

But what is the next step? Or is there any better way to load a custom bundle?

Answer Source

Use the Bundle(path:) constructor and avoid forced unwrapping:

if let bundlePath = Bundle.main.path(forResource: "LiveUI", ofType: "bundle"),
    let bundle = Bundle(path: bundlePath),
    let path = bundle.path(forResource: "...", ofType: nil) {
} else {
    print("not found")

An alternative is to load the bundle using the bundle identifier (defined in the bundle's Info.plist):

let bundle = Bundle(identifier: "com.company.bundle.LiveUI")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download