如何在Swift 3中加载自定义捆绑包

时间:2016-09-05 09:09:17

标签: ios swift swift3

在Objective-C中我这样做:

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

但我似乎无法在swift 3中找到相同的东西

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

但下一步是什么?或者有更好的方法来加载自定义捆绑包吗?

1 个答案:

答案 0 :(得分:18)

使用Bundle(path:)构造函数并避免强制解包:

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

另一种方法是使用捆绑标识符加载捆绑包 (在bundle的Info.plist中定义):

let bundle = Bundle(identifier: "com.company.bundle.LiveUI")