iOS框架捆绑的路径

问题描述 投票:16回答:3

我正在研究iOS的框架,它带有一些数据文件。要将它们加载到Dictionary,我会这样做:

public func loadPListFromBundle(filename: String, type: String) -> [String : AnyObject]? {
    guard
       let bundle = Bundle(for: "com.myframework")
       let path = bundle.main.path(forResource: filename, ofType: type),
       let plistDict = NSDictionary(contentsOfFile: path) as? [String : AnyObject]
    else { 
       print("plist not found")
       return nil 
    }

    return plistDict
}

如果我在带有框架的游乐场中使用它,它可以按预期工作。

但是,如果我使用嵌入在应用程序中的框架,它不再起作用,“路径”现在指向应用程序的捆绑,而不是框架。

如何确保访问框架的捆绑包?

编辑:上面的代码驻留在框架中,而不是在应用程序中。

EDIT2:上面的代码是一个实用函数,不是结构或类的一部分。

ios swift swift3 frameworks bundle
3个回答
41
投票

使用Bundle(for:Type)

let bundle = Bundle(for: type(of: self))
let path = bundle.path(forResource: filename, ofType: type)

更新:

或者通过identifier搜索包(框架包ID):

let bundle = Bundle(identifier: "com.myframework")

3
投票

尝试下面的代码来获取自定义包:

let bundlePath = Bundle.main.path(forResource: "CustomBunlde", ofType: "bundle")
let resourceBundle = Bundle.init(path: bundlePath!)

更新

如果在你的框架中,试试这个:

[[NSBundle bundleForClass:[YourClass class]] URLForResource:@"YourResourceName" withExtension:@".suffixName"];

0
投票

只需指定资源的类名,下面的函数将为您提供与该类关联的Bundle对象,因此如果class与框架相关联,它将提供框架的bundle。

let bundle = Bundle(for: <YourClassName>.self)
© www.soinside.com 2019 - 2024. All rights reserved.