Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you check if SwiftUI is in preview mode?

Is there a way to check if a SwiftUI app is in preview mode? For example, you can check if your app is in development or production mode using #if DEBUG. Can you do something similar to check if you're previewing or not?

like image 927
Ken Mueller Avatar asked Nov 08 '19 03:11

Ken Mueller


2 Answers

You can detect this using ProcessInfo.processInfo.environment["XCODE_RUNNING_FOR_PREVIEWS"]. The value will be "1" at runtime when running in the canvas.

like image 151
arsenius Avatar answered Oct 13 '22 22:10

arsenius


If you like me were looking for an environment variable to use in build scripts which xcode sets when building for SwiftUI previews, it turned out to be ENABLE_PREVIEWS.

SwiftUI were pausing preview when my script updated Info.plist file. To fix that I exit the script at certain point if we are in preview build.

if [ "${ENABLE_PREVIEWS}" = "YES" ]; then
  exit 0;
fi
like image 28
Orkhan Alikhanov Avatar answered Oct 13 '22 21:10

Orkhan Alikhanov