Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't load images from .xcasset in CocoaPods

I'm creating a pod and I have an image asset catalog I'd like to use. In my .podspec file, I have it set up like this:

s.resource_bundles = {
  'MyPodResources' => ['*.xcassets']
}

and the Images.xcassets is in the root directory of the pod.

When I'm try to load images using imageNamed(), it's just not working. I don't get an error or a warning but no images are displayed.

Here's the fun part - if I try to add an image in my Main.storyboard in the example application, I can select the image and it's showing up fine in the Interface Builder. However, when I run the example app, the image is not visible.

I've looked through all issues on GH and still can't find a solution to this ... Is it an Xcode 7/iOS 9 issue?

Thanks!

like image 507
Jure Avatar asked Oct 11 '15 09:10

Jure


3 Answers

in Swift 3:

let bundle: Bundle = Bundle(identifier: "Framework Bundle ID")!
yourImageView.image =  UIImage(named: "imageNameInAssets", in: bundle, compatibleWith: nil)
like image 188
BabakHSL Avatar answered Oct 13 '22 10:10

BabakHSL


In the end, I wrote an extension for UIImage and put it in the pod directory. It looks like this:

class func bundledImage(named: String) -> UIImage? {
    let image = UIImage(named: named)
    if image == nil {
        return UIImage(named: named, inBundle: NSBundle(forClass: MyBasePodClass.classForCoder()), compatibleWithTraitCollection: nil)
    } // Replace MyBasePodClass with yours
    return image
}

I'm using it like: imageView.image = UIImage.bundledImage("icon-grid")

That's it, hope someone finds this useful!

like image 8
Jure Avatar answered Oct 18 '22 21:10

Jure


I had the same issue and found a small but important piece of info about the .podspec file

I was trying to use an image from my pods bundle thats inside a .xcassets in the storyboard, it would show fine in the storyboard but when i ran the app it would crash saying it cant find the resource.

I changed my podspec to include s.resources as well as s.resource_bundles

s.resource_bundles = {
  'SDKRes' => ['SDK/Assets/*']
}

s.resources = ['SDK/Assets/*.{xcassets}']

Then it was able to load the resource properly from the storyboard

like image 2
Fonix Avatar answered Oct 18 '22 20:10

Fonix