iosswiftxcasset

How to build framework with xcassets


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


Solution

  • 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)
        }