我正在研究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:上面的代码是一个实用程序函数,不是结构或类的一部分。
答案 0 :(得分:37)
使用get_attribute
:
Bundle(for:Type)
更新
或按let bundle = Bundle(for: type(of: self))
let path = bundle.path(forResource: filename, ofType: type)
(框架包ID)搜索包:
identifier
答案 1 :(得分:3)
尝试使用以下代码获取自定义捆绑包:
let bundlePath = Bundle.main.path(forResource: "CustomBunlde", ofType: "bundle")
let resourceBundle = Bundle.init(path: bundlePath!)
<强>更新强>
如果在你的框架中,试试这个:
[[NSBundle bundleForClass:[YourClass class]] URLForResource:@"YourResourceName" withExtension:@".suffixName"];
答案 2 :(得分:0)
只需指定资源的类名,下面的函数将为您提供与该类相关联的Bundle对象,因此,如果class与某个框架相关联,它将提供该框架的捆包。
let bundle = Bundle(for: <YourClassName>.self)
答案 3 :(得分:0)
雨燕5
let bundle = Bundle(for: Self.self)
let path = bundle.path(forResource: "filename", ofType: ".plist")
答案 4 :(得分:0)
import class Foundation.Bundle
private class BundleFinder {}
extension Foundation.Bundle {
/// Returns the resource bundle associated with the current Swift module.
static var module: Bundle = {
let bundleName = "ID3TagEditor_ID3TagEditorTests"
let candidates = [
// Bundle should be present here when the package is linked into an App.
Bundle.main.resourceURL,
// Bundle should be present here when the package is linked into a framework.
Bundle(for: BundleFinder.self).resourceURL,
// For command-line tools.
Bundle.main.bundleURL,
]
for candidate in candidates {
let bundlePath = candidate?.appendingPathComponent(bundleName + ".bundle")
if let bundle = bundlePath.flatMap(Bundle.init(url:)) {
return bundle
}
}
fatalError("unable to find bundle named ID3TagEditor_ID3TagEditorTests")
}()
}
来自:Source
---更新---
它提供了 3 种大多数关于如何获取正确 bundle 的注释用法,这非常有用,尤其是在您开发自己的框架或使用 Cocoapods 时。