Access Resources in pod

房东的猫 提交于 2019-12-02 20:51:48

It depends on the version of Cocoapods that you use. With older versions of cocoapods, you could get away with using [NSBundle mainBundle]:pathForResource:ofType:

NSString *bundlePath = [[NSBundle mainBundle] 
    pathForResource:@"MyResourceBundle" ofType:@"bundle"];
NSBundle *bundle = [NSBundle bundleWithPath:bundlePath];

If you are using newer Cocoapods and using spec.resource_bundles instead of spec.resources in your podspec file, you have to avoid mainBundle and replace it with NSBundle bundleForClass, which "Returns the NSBundle object with which the specified class is associated"

Example:

NSString *bundlePath = [[NSBundle bundleForClass:[MyFrameworkClass class]] 
    pathForResource:@"MyResourceBundle" ofType:@"bundle"];
NSBundle *bundle = [NSBundle bundleWithPath:bundlePath];

This tripped me up too. Maybe I'm misunderstanding +bundleWithIdentifier:, but I don't think you can use it to get to a resource bundle inside of your iOS app bundle. See the "Getting Bundles by Identifier" section of the bundle docs for more details.

What does work is +bundleWithPath:, e.g.:

NSString *bundlePath = [[NSBundle mainBundle] pathForResource:@"MyResourceBundle" ofType:@"bundle"];
NSBundle *bundle = [NSBundle bundleWithPath:bundlePath];

I wrapped that inside of a dispatch_once block and call it any time I need to access this bundle.

I'm using the s.resource_bundles syntax in my podspec as well and this works fine with it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!