I have struggled a lot to how to load resource in cocoapods resource_bundle.
The following is what i put in the .podspecs
file.
s.source_files = 'XDCoreLib/Pod/Classes/**/*' s.resource_bundles = { 'XDCoreLib' => ['XDCoreLib/Pod/Resources/**/*.{png,storyboard}'] }
This is what I am trying to do from the main project.
let bundle = NSBundle(forClass: XDWebViewController.self) let image = UIImage(named: "ic_arrow_back", inBundle: bundle, compatibleWithTraitCollection: nil) print(image)
I did see the picture in the XDCoreLib.bundle
, but it return a nil.
I struggled with a similar issue for a while. The resource bundle for a pod is actually a separate bundle from where your code lives. Try the following:
Swift 5
let frameworkBundle = Bundle(for: XDWebViewController.self) let bundleURL = frameworkBundle.resourceURL?.appendingPathComponent("XDCoreLib.bundle") let resourceBundle = Bundle(url: bundleURL!) let image = UIImage(named: "ic_arrow_back", in: resourceBundle, compatibleWith: nil) print(image)
-- ORIGINAL ANSWER --
let frameworkBundle = NSBundle(forClass: XDWebViewController.self) let bundleURL = frameworkBundle.resourceURL?.URLByAppendingPathComponent("XDCoreLib.bundle") let resourceBundle = NSBundle(URL: bundleURL!) let image = UIImage(named: "ic_arrow_back", inBundle: resourceBundle, compatibleWithTraitCollection: nil) print(image)
I don't think any of the other answers have described the relationship to the Podspec. The bundle URL uses the name of the pod and then .bundle
to find the resource bundle. This approach works with asset catalogs for accessing pod images both inside and outside of the pod.
Podspec
Pod::Spec.new do |s| s.name = 'PodName' s.resource_bundles = { 'ResourceBundleName' => ['path/to/resources/*/**'] } end
Objective-C
// grab bundle using `Class` in pod source (`self`, in this case) NSBundle *bundle = [NSBundle bundleForClass:self.classForCoder]; NSURL *bundleURL = [[bundle resourceURL] URLByAppendingPathComponent:@"PodName.bundle"]; NSBundle *resourceBundle = [NSBundle bundleWithURL:bundleURL]; UIImage *podImage = [UIImage imageNamed:@"image_name" inBundle:resourceBundle compatibleWithTraitCollection:nil];
Swift
See this answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With