Main bundle Assets in Swift package previews

Viewed 40

enter image description here

I have the following (screenshot) project setup. Basically simple application with some SwiftUI views placed in the local SPM packages.

While I'm building the application for a real device/simulator everything is good, all assets are loaded properly. SwiftUI preview located in the local package though is not able to display the image from the main bundle (screenshot).

I'm wondering if there is some way to load main bundle assets to SwiftUI previews as well.

1 Answers

You need to load the image from the specific framework bundle, in your case the package.

Your preview/package cannot find an image because it is search for in the wrong bundle.

Do it like this:

Image("test", bundle: .module)

I've an extension on Bundle to find out the correct module from which to load assets, depending on if it is a package or not:

extension Bundle {

    static var current: Bundle {
        #if SWIFT_PACKAGE
        return Bundle.module
        #else
        // swiftlint:disable:next type_name
        class __ { }
        return Bundle(for: __.self)
        #endif
    }

}
Related