How do I load a custom bundle in Swift 3

15,453

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) {
    print(path)
} 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")
Share:
15,453
Ondrej Rafaj
Author by

Ondrej Rafaj

MD of a London / Prague based mobile agency ... and a big fan of iOS

Updated on June 19, 2022

Comments

  • Ondrej Rafaj
    Ondrej Rafaj almost 2 years

    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?