avatar
Published on

Detecting if SwiftUI is running in a Preview in Xcode

Authors
  • avatar
    Name
    Mick MacCallum
    Twitter
    @0x7fs

When building SwiftUI apps, you'll often try to separate out unnecessary logic from your views so they can simply render input data. But this isn't always possible. There are cases where you'll need to write code in your SwiftUI View, which you expect to run in your app, but without running in the Preview in Xcode.

As of iOS 18, Apple doesn't provide a direct way to do this, but it is possible by reading the XCODE_RUNNING_FOR_PREVIEWS environmental variable. Here's an extension of UIDevice which accesses this value to determine if the app is running in a preview.

import UIKit

extension UIDevice {
    static let isPreview: Bool = {
        #if targetEnvironment(simulator)
        guard let flag = ProcessInfo.processInfo.environment[
            "XCODE_RUNNING_FOR_PREVIEWS"
        ] else {
            return false
        }

        return flag == "1"
        #else
        return false
        #endif
    }()
}

You can then use the extension within your view to only run code when not running in a preview.

var body: some View {
    content.onAppear {
        if !UIDevice.isPreview {
            checkAuthorizationStatus()
        }
    }
}