Path to bundle of iOS framework

2019-04-04 00:15发布

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?

EDIT: the code above resides in the framework, not in the app.

EDIT2: the code above is a utility function, and is not part of a struct or class.

3条回答
放荡不羁爱自由
2楼-- · 2019-04-04 01:03

Try below code to get the custom bundle:

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

Update

If in your framework, try this:

[[NSBundle bundleForClass:[YourClass class]] URLForResource:@"YourResourceName" withExtension:@".suffixName"];
查看更多
我只想做你的唯一
3楼-- · 2019-04-04 01:19

Use Bundle(for:Type):

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

Update:

or search the bundle by identifier (the frameworks bundle ID):

let bundle = Bundle(identifier: "com.myframework")
查看更多
不美不萌又怎样
4楼-- · 2019-04-04 01:19

Simply specify the class name of the resource and below function will give you the Bundle object with which the class is associated with, so if class is associated with a framework it will give bundle of the framework.

let bundle = Bundle(for: <YourClassName>.self)
查看更多
登录 后发表回答