Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 534
Jeremy Avatar asked Jul 24 '20 17:07

Jeremy


People also ask

How do I debug a SwiftUI preview?

You can attach the debugger to the app running in the preview by using Debug menu -> Attach to Process and choose your app. Now you can press Debug View Hierarchy button in the toolbar on the bottom of Xcode to run visual debugger.

What is preview content in Xcode?

Overview. When you create a custom View with SwiftUI, Xcode can display a preview of the view's content that stays up to date as you make changes to the view's code. You define a structure that conforms to the PreviewProvider protocol to tell Xcode what to display. Xcode shows the preview in a canvas beside your code.

How do I Preview Dark mode in Xcode?

Xcode 11's Interface Builder also comes with a new feature for you to preview the screen in dark mode. Open any of your storyboards file, you should find the Interface Style option in the device menu. Click the dark mode icon to switch to the dark mode.


1 Answers

I believe this is an Xcode bug, but I've thought of a workaround.

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.

like image 108
Jeremy Avatar answered Sep 29 '22 20:09

Jeremy