5

I tried to build an framework with its own image and it compiles fine. However, when I include my framework in another project, it crashes when loading the image, any idea?

ImageTest (my framework)

public class ImageTest {
    open func getImage() {
        return #imageLiteral(resourceName: "IMG_0745")
    }
}

My project

import ImageTest
...
...

override func viewDidLoad() {
    super.viewDidLoad()

    let imageView = UIImageView(image: ImageTest.getImage()) // crash !
    imageView.center = view.center
    view.addSubview(imageView)
}

enter image description here

Willjay
  • 6,381
  • 4
  • 33
  • 58

4 Answers4

5

The image is in ImageTest framework. When you execute this code, return #imageLiteral(resourceName: "IMG_0745"), it looks at the Image.xcassets of ImageTest project and when it does not find the image there, it results in the crash.

Change your code to use bundle param of init function

open func getImage() {
        return UIImage(named:"IMG_0745", bundle:Bundle(for: self), compatibleWith:nil)
    }
Puneet Sharma
  • 9,369
  • 1
  • 27
  • 33
4

In Swift 5,

UIImage(named: "IMG_0745", in: Bundle(for: xxxYourViewController.self), compatibleWith: nil)
Anish
  • 595
  • 1
  • 4
  • 16
1

In Swift 4 now it is

UIImage(named: "IMG_0745", in: Bundle(for:self), compatibleWith: nil)
Reimond Hill
  • 4,278
  • 40
  • 52
0

You could use such extension per framework, if you lack any classes around:

extension UIImage{
    convenience internal init?(namedInBundle name: String, with configuration: UIImage.Configuration? = nil) {
        class ClassForBundleIdentification{}
        let bundle = Bundle(for: ClassForBundleIdentification.self)
        self.init(named: name, in: bundle, with: configuration)
    }
}

then you could use it somehow along these lines:

public class ImageTest {
    public init(){}
    open func getImage() -> UIImage? {
        UIImage(namedInBundle: "screenshot1")
    }
}
Radek
  • 581
  • 4
  • 12