How to load resource in cocoapods resource_bundle

Solution 1:

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)

Solution 2:

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.

Solution 3:

This will work

In .podspec add s.resources in addition to s.resource_bundles (pod install afterwards)

s.resources = 'XDCoreLib/Pod/Resources/**/*.{png,storyboard}'

Then in your code, its as easy as:

let image = UIImage(named: "image_name.png", in: Bundle(for: type(of: self)), compatibleWith: nil)

Note: You may need to run pod install after updating the .podspec to have the changes to your Xcode proj

Solution 4:

You can just check the ID of the Bundle by selecting the Pods project, selecting the desired target, and making sure you're on the General tab.

enter image description here

Then in code you can load say an image in that Pod like so:

backgroundImageView.image = UIImage(named: "business_fellas", in: Bundle(identifier: "org.cocoapods.StandardLibrary3-0"), compatibleWith: nil)