How to build framework with xcassets
Asked Answered
C

4

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

Carnivorous answered 27/11, 2017 at 10:1 Comment(0)
K
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)
    }
Kreager answered 27/11, 2017 at 10:29 Comment(0)
D
4

In Swift 5,

UIImage(named: "IMG_0745", in: Bundle(for: xxxYourViewController.self), compatibleWith: nil)
Digitalis answered 2/11, 2020 at 16:21 Comment(0)
F
1

In Swift 4 now it is

UIImage(named: "IMG_0745", in: Bundle(for:self), compatibleWith: nil)
Frater answered 18/9, 2018 at 11:32 Comment(0)
J
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")
    }
}
Jedlicka answered 3/3, 2023 at 6:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.