3 Replies
      Latest reply on Sep 4, 2019 6:39 PM by justinscott
      sjmadsen Level 1 Level 1 (0 points)

        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.

        • Re: Conditionally compiling SwiftUI views at preview time
          sjmadsen Level 1 Level 1 (0 points)

          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.)