xcodeswiftuipreviewswiftui-previewsxcode-build-phase

Detect if build is triggered from SwiftUI Preview in Build Phases - Run Script


Is there any way to detect if the build was triggered by the SwiftUI Preview from inside Build Phases - Run Script?

I'm using swiftlint with --fix --format, the problem is when I have the Preview open it sometimes triggers a build, which often changes the file while I'm typing, which then brings up the "keep changes/revert" dialog. Keeping the changes often leads Xcode to crash. Ideally, I'd like to do something like this:

if buildWasTriggeredBySwiftUIPreview then
    swiftlint
else 
    swiftlint --fix --format && swiftlint
fi

Solution

  • Update

    This no longer works in xCode 16 (developer forum discussion). Detecting it during runtime can be achieved with this. That sadly doesn't help for the build phase, though:

    let isXcodePreview = ProcessInfo.processInfo.environment["XCODE_RUNNING_FOR_PREVIEWS”] != nil
    

    Previous Answer

    Thanks to Sweeper, this works:

    if [ "${ENABLE_PREVIEWS}" = "YES" ]; then 
        swiftlint
    else 
        swiftlint --fix --format && swiftlint  
    fi