Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load resource in cocoapods resource_bundle

Tags:

ios

cocoapods

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.

like image 364
Joe SHI Avatar asked Feb 29 '16 05:02

Joe SHI


2 Answers

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) 
like image 200
Quaid Avatar answered Sep 18 '22 09:09

Quaid


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.

like image 21
Matt Robinson Avatar answered Sep 22 '22 09:09

Matt Robinson