Why does Archive fail if there is code for SwiftUI Previews in the Preview Content folder?

Viewed 1235

In my SwiftUI app, I have put some sample model objects in Xcode's "Preview Content" folder. I only access them in my SwiftUI PreviewProviders. My understanding is that the code/assets in this folder are only used for previewing in the Canvas. My previews work properly. I'm using Xcode 11.6 (11E708).

However, when I go to Archive my app, it fails because it cannot find these sample model objects. I was under the impression that PreviewProvider code is not build into the final binary as of Xcode 11. See this question and this screenshot from the Xcode 11 release notes.

(Curiously, I am able to compile with the Release configuration. It's just Archive that fails.)

As a workaround, I can put the #if DEBUG/#endif wrappers around my PreviewProvider but the above screenshot indicates that shouldn't be necessary.

Do I misunderstand how the "Preview Content" folder works?

2 Answers

Edit: Nevermind, this approach "works" but the preview code is still in the final archive, so it doesn't really help anything.

I put all my preview test data in its own `PreviewProvider` so that I can access it in other Previews. The Archive still succeeds, and the test data will get stripped in the final Archive. No `#if DEBUG` is needed.

Example (specific to my own use case):

struct PreviewData: PreviewProvider {
    static var previews: some View {
        Text("This is test data for use in other previews.")
    }

    // Use enums for namespacing if desired
    enum Choices {
        static let deals = Choice(id: UUID().uuidString, text: "I want the best deals.", iconName: "bestDealsIcon")
        static let technology = Choice(id: UUID().uuidString, text: "I love technology!", iconName: "technologyIcon")
    }

Then I can access PreviewData.Choices.deals in other PreviewProviders.

I had a very similar issue occur, only I was building an App Clip for an existing app. I couldn't compile with the release scheme or archive for distribution with neither versions of Xcode 12.5.1 or 13.0.

The solution was to include the Preview Content directory under the development assets of the parent app's target, not the App Clip target itself. As a result, I got it to work in all scenarios, including SwiftUI previews, release builds and archiving the parent app for distribution.

Related