Reputation: 3043
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!
Upvotes: 12
Views: 6104
Reputation: 11597
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
Upvotes: 2
Reputation: 56
I bumped into this issue and fixed it by the following method.
I put my icon images in Assets.xcassets at first, but I can't read my images in it.
Put your icon images in bundle. Creating a bundle is easy.
s.resource_bundles = {'<YourBundleName>' => ['*.bundle']}
Note that if your enter a different name here will rename your bundle!
class ImageHelper {
static func image(_ name: String) -> UIImage? {
let podBundle = Bundle(for: ImageHelper.self) // for getting pod url
if let url = podBundle.url(forResource: "<YourBundleName>", withExtension: "bundle") { //<YourBundleName> must be the same as you wrote in .podspec
let bundle = Bundle(url: url)
return UIImage(named: name, in: bundle, compatibleWith: nil)
}
return UIImage()
}
ImageHelper.image("<YourImageName>")
Hope this helps.
Upvotes: 1
Reputation: 772
in Swift 3:
let bundle: Bundle = Bundle(identifier: "Framework Bundle ID")!
yourImageView.image = UIImage(named: "imageNameInAssets", in: bundle, compatibleWith: nil)
Upvotes: 1
Reputation: 3043
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!
Upvotes: 9