WidgetKit: Image from Assets.xcassets fails to load (errno = 2), but direct file access works

1 day ago 1
ARTICLE AD BOX

I am developing an iOS Widget using SwiftUI and WidgetKit. I am trying to load a simple background image into the widget, but I am facing a persistent issue where images inside the Asset Catalog (Assets.xcassets) are not found, resulting in a black background.

The Setup:

I have a dedicated Assets.xcassets inside my Widget Extension folder.

The image set (bg1) has its Target Membership checked for the Widget Extension.

I have tried cleaning the build folder (Shift+Cmd+K) and deleting derived data multiple times.

The Problem: When I try to load the image using the standard SwiftUI approach or even by forcing the Bundle, the image does not appear.

Attempt 1 (Standard):

Swift

Image("bg1") .resizable() // Result: Shows a placeholder/empty space.

Attempt 2 (Explicit Bundle): I tried to force load it from the extension's bundle using UIImage:

Swift

private class BundleFinder {} // Dummy class to find bundle func getWidgetImage() -> UIImage { let bundle = Bundle(for: BundleFinder.self) if let image = UIImage(named: "bg1", in: bundle, compatibleWith: nil) { return image } print("Image not found in bundle") return UIImage() }

Result: The console throws the following error: fopen failed for data file: errno = 2 (No such file or directory)

The Workaround (What actually worked): The only way I could get the image to show up was by deleting it from the Asset Catalog and dragging the .jpg file directly into the Project Navigator (into the Extension folder), checking "Copy items if needed" and the Target Membership.

Then, loading it via raw path works perfectly:

Swift

let bundle = Bundle(for: BundleFinder.self) if let path = bundle.path(forResource: "bg1", ofType: "jpg"), let image = UIImage(contentsOfFile: path) { return image // This works! }

My Question: Why is Assets.xcassets failing to provide the image to the Widget Extension despite correct Target Membership, resulting in errno = 2? Is there a known bug in Xcode or WidgetKit regarding Asset Catalogs in Extensions, or is there a specific build setting required to make the Asset Catalog accessible?

Read Entire Article