SwiftUI: drop-in bundle images found by file name with no UIKit and no asset catalog (ImageIO + Image(decorative:))
Wanted non-engineers to add a logo by copying a PNG into a folder, with the app deciding at runtime whether a file exists for a given name and falling back to a monogram otherwise. Constraints: no UIKit in app code, Xcode 26.2 project with file-system-synchronized groups (objectVersion 77), iOS 18+.
Why not the asset catalog: Image("name") gives no way to ask whether the image exists; a missing one just draws nothing. The only existence check is UIImage(named:).
What worked:
guard let url = Bundle.main.url(forResource: name, withExtension: "png"),
let source = CGImageSourceCreateWithURL(url as CFURL, nil),
let cg = CGImageSourceCreateImageAtIndex(source, 0, nil) else { return nil }
return Image(decorative: cg, scale: 1) // then .resizable().scaledToFit()Observed:
- A PNG placed in a subfolder of a synchronized group (Supper/Resources/StoreLogos/store-x.png) was copied to the ROOT of the .app bundle, not into a StoreLogos directory. So look it up with no subdirectory:, and give the files a prefix (I used store-) because the bundle root is one flat namespace.
- Adding the file needed no project.pbxproj change; the next build picked it up.
- Deleting the file and rebuilding removed it from the built .app (checked with find on the product).
- Cache both hits and misses in a dictionary/set; a grid redraw otherwise hits the bundle for every tile.
- For logos, force .environment(\.colorScheme, .light) on the well so token colours resolve to their light values and the logo keeps a white ground in dark mode.
Testing without UIKit: write a 2x3 CGContext image to a temp file with CGImageDestination and assert the loader returns width 2, height 3; and a repo-level test that every file in the folder matches a name the app would actually look for, so a typo like store-krogr.png fails CI instead of silently never showing.
Limit: PNG/JPEG only. SVG and PDF vectors still need the asset catalog.