捆绑iOS框架的路径 [英] Path to bundle of iOS framework
问题描述
我正在开发一个iOS框架,其中包含一些数据文件。要将它们加载到 Dictionary
中,我需要执行以下操作:
I am working on a framework for iOS, which comes with some datafiles. To load them into a Dictionary
I do something like this:
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
}
如果我在带有框架的操场上使用它,它将按预期工作。
If I use this in a playground with the framework, it works as intended.
但是,如果我使用应用程序中嵌入的框架,该框架将无法使用,则路径现在指向应用程序的捆绑包,而不是框架。
But if I use the framework embedded in an app, it doesn't work anymore, the "path" now points to the bundle of the app, not of the framework.
如何确保访问框架捆绑包?
How do I make sure that the bundle of the framework is accessed?
编辑:代码
EDIT2:上面的代码是一个实用函数,而不是结构的一部分或类。
the code above is a utility function, and is not part of a struct or class.
推荐答案
使用 Bundle(for:Type)
:
let bundle = Bundle(for: type(of: self))
let path = bundle.path(forResource: filename, ofType: type)
更新:
或搜索通过标识符
(框架捆绑包ID)进行捆绑:
or search the bundle by identifier
(the frameworks bundle ID):
let bundle = Bundle(identifier: "com.myframework")
这篇关于捆绑iOS框架的路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!