SwiftUI image from Bundle.main not working

I have a project with a single asset image. In the dependency package, I am attempting to preview using the image in the project using Bundle.main. I just get a blank.

How can I get this to work?

Sample project here: https://github.com/AaronBratcher/SwiftUIPreviewProblem

Hi, when you develop a swift package, you should add directly to it bundle resources that should be used. Swift Package dont' have access directly to app asset, because are package :) And should developed as reusable resources, used in another app without modification.

Here the docs for add bundle resources to Swift Package https://developer.apple.com/documentation/xcode/bundling-resources-with-a-swift-package

Bye Rob

Thanks for offering the sample project! That really helps to see the issue you're running into.

So this behaves correctly because when previewing in a static library all by itself there is no main bundle. When building and running this within the context of an app target using Bundle.main will work just fine, of course because everything is loaded together in memory. But in the context of previewing a single package by itself, Previews is able to launch its own empty app and inject the package library into it. Bundle.main will point to that app bundle.

The advice above to make sure you put the resources you want into the package is a good idea to resolve this. It may be possible to work around this by always previewing the package library when you have the app target selected in the scheme, but that still is working around a circular dependency that is best resolved by making sure the app target code depends on library resources and not the other way around.

The assets will be in whatever project the package is used in. To put the assets into the package itself is not good and, unfortunately, there isn't a Preview Content option with packages.

Got it, so if I understand your goal, you are using the main bundle of any given project as a "shared resources container" that libraries can assume will be populated.

Can you file a feedback with this request? This isn't a normal course because we'd usually recommend actually pulling resources out into a shared framework that all components depend on. But you rightly point out that it just so happens to work when build-and-running that dependent libraries have a main bundle that gives you a shared location for resources. We can use this feedback request to see what we can do here.

Hi, mmm it seems an interesting use case, but what are the benefits on this approach? The main bundle should be app single dependency. if we have the needs of pass data to the package itself , probably some sort of dependency injection could be the best option. I'm not sure that put a main.bundle a shared resources container on different framework/package is the best approach, but probably I miss some point.

Bye Rob

SwiftUI image from Bundle.main not working
 
 
Q