Detecting Xcode Previews
This reference article covers how to use environment values to detect if a process is running in a Xcode preview.
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.
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.
EnvironmentValues is a collection of environment values propagated through a view hierarchy. If you want to know more check the official documentation.
We can extend this collection by adding a boolean variable, called isPreview
, that accesses the process information agent and returns true
only if the value of the “XCODE_RUNNING_FOR_PREVIEWS”
key in the environment from which the process was launched is equal to 1. This of course only happens when the code is built to be executed in a preview.
extension EnvironmentValues {
var isPreview: Bool {
return ProcessInfo.processInfo.environment["XCODE_RUNNING_FOR_PREVIEWS"] == "1"
}
}
As always, Apple's documentation is the perfect place to find additional information on ProcessInfo
as well.
We now focus on how to use these variables.
To read a value from the EnvironmentValues
structure, declare a property using the Environment
property wrapper and specify the value’s key path. This is a simple example of how you can use our isPreview environmental value.
struct ContainerView: View {
@Environment(\\.isPreview) var isPreview
var body: some View {
if isPreview {
VStack {
Text("This is")
Text("a Preview")
.fontWeight(.bold)
}
.foregroundColor(.pink)
} else {
VStack {
Text("This is")
Text("not a Preview")
.fontWeight(.bold)
}
.foregroundColor(.blue)
}
}
}
If you run the code above in the preview you will see the label "This is a preview", on the other hand on a simulator or a real device you will see the label "This is not a preview".
In this reference article we have explored the world of Xcode Previews, a fantastic development tool for quickly iterating on UI projects. There are simply times when we want to use different data input for our previews and to do this we have extended the environment variables.