Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run SwiftUI preview from SPM Package

I am developing a package of Swift Package Manager where SwiftUI views need to be included.

Every SwiftUI view should have a preview.

However, when I try to run a preview of any view I get the following error: enter image description here

I found a way where if I change the package scheme to the main target scheme it becomes work. But using this way I have to switch between schemes all the time and the main target needs to be built every time I want to run a preview of a package.

Is it possible to run SwiftUI preview somehow directly from SPM Package without building the main target?

like image 685
Julian D. Avatar asked Jan 14 '20 10:01

Julian D.


2 Answers

What you need is to add in your swiftpackage declaration a platform target such as iOS see example below (with iOS(.v13)):

let package = Package(
    name: "NAME",
    platforms: [.iOS(.v13)],
    products: [
        // Products 
    ],
    dependencies: [
        // Dependencies declare other packages that this package depends on.
        // .package(url: /* package url */, from: "1.0.0"),
    ],
    targets: [
        // Targets
        // Test Targets
    ]
)

And now, make sure you use the same target for the preview. You can add more of course.

enter image description here

like image 95
Daniel Bastidas Avatar answered Nov 07 '22 22:11

Daniel Bastidas


Xcode 12

With Xcode 12 the SwiftUI Preview just works 'as-should' in standalone Package

demo

Xcode 11+

Is it possible to run SwiftUI preview somehow directly from SPM Package without building the main target?

No, at least till now (Xcode 11.4beta3). Preview is a variant of Simulator and it needs UI executable to setup full-functional run-time context for your view preview.

Solution (from practice): setup SwiftUI executable target that in parallel contains all files from package (or package itself, depends) and perform all SwiftUI development it it, but package itself build during continuous integration process (including unit-testing).

like image 5
Asperi Avatar answered Nov 07 '22 22:11

Asperi