iosswiftxcasset

Loading image from xcassets causes assertion failure


I am using the xcassets folder to store themable images. For the default theme, the image is always present in the xcassets, but for other themes, the image is optional, which will result in the use of the default image.

Pseudo code:

struct ThemeImage {
    static let standard = UIImage(named: "default-logo")!

    static func themedImage(for theme: String) -> UIImage {
        return UIImage(named: "\(theme)-logo") ?? ThemeImage.standard
    }
}

Now when I try to load the image for a theme, but the asset does not exist, the app will instantly crash, reporting the following error:

*** Assertion failure in -[_UIImageCGImageContent initWithCGImage:scale:], /BuildRoot/Library/Caches/com.apple.xbs/Sources/UIKitCore_Sim/UIKit-3901.4.2/_UIImageContent.m:336
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Need an imageRef'

The documentation clearly states

Returns

An object containing an unconfigured version of the image, or nil if the method could not find the specified image.

Does anyone know what is happening or why the app crashes instead of returning nil?


Solution

  • The issue was related to the xcassets folder after all. I had some colours in the folder too, which had the same name as the image.

    Meaning UIColor(named: "default-logo") and UIImage(named: "default-logo") will cause the application to crash, even though both resources are present and valid in the xcassets folder.

    The name of these assets needs to be unique.