Skip to content

Instantly share code, notes, and snippets.

@kraigspear
Created June 19, 2023 07:43
Show Gist options
  • Save kraigspear/5ec46f779172e9f57cd07285bbd5365e to your computer and use it in GitHub Desktop.
Save kraigspear/5ec46f779172e9f57cd07285bbd5365e to your computer and use it in GitHub Desktop.
Detect if running in Previews or Unit Test
public extension EnvironmentValues {
var isPreview: Bool {
#if DEBUG
return ProcessInfo.processInfo.environment["XCODE_RUNNING_FOR_PREVIEWS"] == "1"
#else
return false
#endif
}
var isUnitTest: Bool {
#if DEBUG
return ProcessInfo.processInfo.environment["XCTestConfigurationFilePath"] != nil
#else
return false
#endif
}
}
struct MyView: View {
@Environment(\.isPreview) var isPreview
var body: some View {
Group {
if isPreview {
Text("This is a preview!")
} else {
Text("This is not a preview!")
}
}
}
}
// Make sure we don't show SwiftUI during Unit Test
import SwiftUI
@main
struct KeepSakeCardsApp: App {
@Environment(\.isUnitTest) var isUnitTest
var body: some Scene {
WindowGroup {
if !isUnitTest {
HomeView(client: .live)
} else {
EmptyView()
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment