Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - Pod images not loading (not found, returns nil)

I’ve created a new pod component as per instructions on CocoaPods website. Now I have the following structure within my Pods:

  • Pods (folder)

    • MyComponent (folder)

      • MyComponent.swift

      • Resources (folder)

        • name_of_image.png

However, when I try to call:

UIImage(named: “name_of_image”)

from MyComponent.swift, I get a "nil" return.

I’ve read solutions that include creating a bundle for my component, but I haven’t found a proper way to generate it myself. Any advice would be nice.

Thanks

like image 464
Armin Avatar asked Feb 09 '23 10:02

Armin


2 Answers

You can't (shouldn't) use UIImage(named:) within a Pod. This will load an image from your app instead of from the Pod.

You need to get your Pod's NSBundle first and then use it to load the image. You can get the NSBundle using any class from your Pod.

let bundle = NSBundle(forClass: ClassFromYourPod.self)
let image = UIImage(named: "xyz", inBundle: bundle, compatibleWithTraitCollection: nil)
like image 106
fluidsonic Avatar answered Feb 10 '23 22:02

fluidsonic


This worked for me if you import a png directly without xcassets

    let bundle = Bundle(for: ClassInsidePod.self)
    let image = UIImage(named: "YourImageName", in: bundle, compatibleWith: nil)
    imageView.image = image

But, if you are testing in the Example project, you need to update the pods in that project with pod update. In my case, before doing that, it was always returning nil

like image 21
Oscar J. Irun Avatar answered Feb 10 '23 22:02

Oscar J. Irun