Detecting Xcode Previews

This reference article covers how to use environment values to detect if a process is running in a Xcode preview.

Detecting Xcode Previews

Since it was announced in 2019, SwiftUI developers have been making extensive use of the new canvas. The canvas allows you to get a quick preview of what you're programming and, especially for frontend developers, is a great help to get going quickly.

Xcode statically discovers preview providers (PreviewProvider) in your project and generates previews for any providers currently open in the source editor. Xcode generates the preview using the current run destination as a hint for which device to display.

Apple Developer Documentation
Apple Developer Documentation: PreviewProvider

However, it is also often useful to know when Xcode is or is not running the code in a preview in order to conditionally choose which data to use to build our app UI. There is no official built-in way to do this. However, we can include in Apple's environment values an additional value that helps us with our goal.

Let's have a look. Become a free member or log in to proceed.