1

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
1
  • 1
    Does this answer your question? It seems like you can just check an environment variable. Commented Jan 19, 2024 at 8:57

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

Comments

0

Do not forget to activate Legacy Previews:
"Editor > Canvas > Use Legacy Previews Execution"

2 Comments

Does the flag not work in Xcode 16 anymore with the default preview?
No , you can see more infos here : forums.developer.apple.com/forums/thread/761439

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.