Conditionally compiling SwiftUI views at preview time

Is it possible to detect when Xcode is building my SwiftUI code for a live preview?


I am working with Core Data managed objects as the data source for SwiftUI views, but they need to be created within a managed object context. At preview time, it's not obvious how to get at the app's persistent container or an existing managed object context. Ideally, I'd prefer to create a temporary store in memory, anyway, both for speed and to not pollute the data used when I run the app.


I'm hoping there is either a compiler flag (like the existing DEBUG one) or something in the process environment that signals that the code is either being built for a preview or is running in preview mode.

Replies

Following my usual pattern of figuring things out soon after posting a question publicly, I discovered a few things this afternoon.


There is an environment variable set when Xcode runs a build for previews: ENABLE_PREVIEWS = YES. This doesn't help my question above, but it does let me skip my SwiftLint build phase. I've long had issues with the use of @IBDesignables in a storyboard and SwiftLint rewriting files (through the autocorrect feature) fighting over a file's "newness" and getting lots of pop-ups about reverting or keeping Xcode's version. I don't know yet if this environment variable will help with that.


To my original question, yes, Xcode does indeed set an environment variable in the process when it's running code for the purpose of generating a preview: XCODE_RUNNING_FOR_PREVIEWS = 1.


I'm still getting a blank preview canvas after setting up a different managed object context and seeding it with some data. If I don't reference the objects in the SwiftUI view (by instead using static text), I'll see things. I'll update this thread again when I figure more out.


(Also, since neither of those environment variables are documented anywhere, it's safe to say that this could change anytime.)

Hey sj, any luck here? I too am trying to figure out how to get SwiftUI previews and Core Data playing nicely, and it's been slow going...

I discovered today that there seem to be 3 different "universes" for my Core Data app's state (all using the same managed object context):

1. What I see in the Canvas view while I'm not in preview mode

2. What I see in the Canvas view whil I'm in preview mode

3. What I see in the Simulator when I build and run my app


Universe 1 only has data added to it when I create mock Core Data objects for the purpose of live previews, but since I never save the context from a static canvas preview, this data doesn't persist, which is exactly what I want.