You are shipping an iOS app, and the build needs to do a little more than compile. A beta build should wear a ribbon on its icon, so nobody installs it and thinks it is production. TestFlight should say what changed, taken from the pull requests that actually merged. A missing translation should fail the build, not show up as a raw key on a phone in another language. SwiftGen should keep the asset names in sync with the catalogs.
I keep those checks and tasks on an iOS app I ship at Dawn Technology. I used to solve each of those with a tool I installed. ImageMagick stamped the ribbon. The GitHub CLI and jq wrote the TestFlight notes. SwiftGen came from Homebrew. When pinning a tool as a CocoaPod was easier than checking a binary into the repo, that is what I did. On my own Mac this is comfortable. The tools are on PATH, I know which versions I have, and a script that starts with which convert just works.
It stops working the moment the build happens on a machine that does not have that history.
Xcode Cloud gives you a clean Mac for the build. On the images I get, that Mac is often still Intel. Homebrew has dropped Intel support, so the usual brew install at the start of a CI script is no longer a plan. There is no tap from your laptop, no Pods directory unless you bring CocoaPods back on purpose, and no formula you installed three years ago. What the machine does have is Xcode. And Xcode includes a Swift compiler.
That compiler is enough. I moved the work into Swift files that live in the repository. A short shell script still starts them, because Xcode’s build phases and Xcode Cloud’s hooks are shell. Swift does the actual work. The same files run when I build locally and when Xcode Cloud builds after a push. Nobody has to install anything before the build can succeed.
When you open Terminal on your own Mac, you get the shell you configured. Homebrew is on PATH if you put it there. The tools you installed last year are still there. A Run Script phase does not work like that, and an Xcode Cloud hook works even less like that.
Xcode starts the script with a short PATH. It does not load your .zshrc. Homebrew’s prefix is /usr/local on Intel and /opt/homebrew on Apple silicon, so a script that hardcodes one of those already fails on the other kind of laptop. On a current Xcode Cloud image the Intel prefix is a dead end anyway, because Homebrew no longer ships bottles for it.
So I stopped asking what I could install, and started from what is already there:
xcrun, swift, swiftc, agvtool, and git come with Xcode and the system.If a tool is not on that list, you have two choices. You can carry it with the repo, which means downloading it on every clean build and hoping the download URL, the architecture, and the code signature still line up. Or you can do the job with the compiler that is about to build the app. I do the second one unless the tool is a real product I do not want to reimplement. Sentry’s upload CLI is the example I kept. ImageMagick is the example I threw out.
Xcode Cloud does not invent a new scripting system. It looks for three filenames in a directory called ci_scripts at the root of the repository:
ci_post_clone.sh runs after the clone, before dependencies are resolved and before the build. This is where I adjust the version number, trust package plugins, and prepare icons and release notes.ci_pre_xcodebuild.sh runs just before xcodebuild, if you need a last change once the environment is fully in place.ci_post_xcodebuild.sh runs after xcodebuild. This is where an App Store build can do something that only makes sense once an archive exists.The working directory for those scripts is ci_scripts itself, not the repository root. That surprises people the first time a relative path fails. The shell is whatever shebang you put on the file. I use zsh, and every hook starts the same way:
#!/bin/zsh
set -euo pipefail
: "${GITHUB_TOKEN:?GITHUB_TOKEN variable is not set}"
set -euo pipefail is worth being picky about. -e stops the hook when a command fails, instead of continuing into a build that is already wrong. -u treats an unset variable as an error, which catches a typo in $GITHUB_TOKEN immediately. -o pipefail makes a pipeline fail when any part of it fails, not only the last command. Without that, agvtool … | xargs can succeed even when agvtool did not.
The line that starts with : is a way to require a variable. If GITHUB_TOKEN is missing or empty, the shell aborts and prints the message. I would rather the clone hook fail in the first second than spend time wondering why “What to Test” is an empty file in TestFlight. On Xcode Cloud you set that token as a secret on the workflow. Locally you export it before you run the script by hand.
The hook should stay thin. Once the environment is known to be valid, it hands off to Swift:
readonly SCRIPT_DIR="${0:A:h}"
readonly REPO_ROOT="${CI_PRIMARY_REPOSITORY_PATH:-$(cd "${SCRIPT_DIR}/.." && pwd)}"
xcrun swift "${SCRIPT_DIR}/generate_release_notes.swift" "$REPO_ROOT" \
"${REPO_ROOT}/TestFlight/WhatToTest.en-US.txt"
${0:A:h} is zsh for “the directory this script lives in, after resolving symlinks.” CI_PRIMARY_REPOSITORY_PATH is an environment variable Xcode Cloud sets to the clone. When you run the same hook on your laptop that variable is absent, so the fallback walks up from ci_scripts to the repo root. That is the same layout either way. You do not want a second copy of the path logic for local experiments.
xcrun swift is the part I would not replace with a bare swift. A shebang of #!/usr/bin/env swift is pleasant on a laptop where the toolchain is on PATH. In the hook I do not want to depend on that. xcrun uses the toolchain selected for the build, which is the one you configured in the Xcode Cloud workflow. If you later pin a newer Xcode, the scripts follow it.
A cloud hook runs once. Interpreting a Swift file with xcrun swift takes a moment, and that moment is invisible next to an archive. I reserve compilation and caching for checks that run on every incremental build. For release notes, interpretation is the simpler tool.
The file still starts with a shebang, so I can also run it directly while I am writing it:
#!/usr/bin/env swift
import Foundation
enum ScriptError: Error, CustomStringConvertible {
case invalidArgs
case gitRemote
var description: String {
switch self {
case .invalidArgs:
return "Usage: generate_release_notes.swift <repo-root> <output-file>"
case .gitRemote:
return "failed to read git remote origin URL"
}
}
}
func runGitRemote(repoRoot: String) throws -> String {
let process = Process()
process.executableURL = URL(fileURLWithPath: "/usr/bin/git")
process.arguments = ["-C", repoRoot, "remote", "get-url", "origin"]
let stdout = Pipe()
process.standardOutput = stdout
try process.run()
process.waitUntilExit()
let output = String(data: stdout.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8)?
.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
guard process.terminationStatus == 0, !output.isEmpty else {
throw ScriptError.gitRemote
}
return output
}
This is the Swift version of a backtick. Process runs /usr/bin/git with an explicit working directory, and the exit status is a real value you can refuse to ignore. I ask git for remote get-url origin instead of hardcoding the GitHub owner and name. The clone on Xcode Cloud and the clone on my laptop can use different URL shapes, SSH or HTTPS, and both contain github.com plus the owner and the repo. Stripping a trailing .git and splitting on github.com: or github.com/ covers the remotes I actually see.
From that owner and name the script calls the GitHub search API for merged pull requests. It keeps the ones that have a merged_at timestamp and writes lines of the form merged_at - title into TestFlight/WhatToTest.en-US.txt. Xcode Cloud picks that file up as the TestFlight test information for the build. You get a notes file that tracks the repo, without a step that only exists in someone’s head.
Calling the API is the part that does not look like a script at first. URLSession is asynchronous. A Swift script that reaches the end of the file exits, and it will do that while the request is still in flight if you do not wait. I use a semaphore:
func fetch(_ request: URLRequest) throws -> Data {
var outcome: Result<(Data, URLResponse), Error>?
let semaphore = DispatchSemaphore(value: 0)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
if let error {
outcome = .failure(error)
} else if let data, let response {
outcome = .success((data, response))
}
semaphore.signal()
}
task.resume()
semaphore.wait()
let (data, response) = try outcome!.get()
let status = (response as? HTTPURLResponse)?.statusCode ?? -1
guard (200..<300).contains(status) else {
let body = String(data: data, encoding: .utf8) ?? ""
throw ScriptError.http(status, body)
}
return data
}
The token is the same environment variable the shell already required. Reading it again in Swift means the script still fails clearly when someone runs the Swift file on its own and forgets to export the token:
let token = ProcessInfo.processInfo.environment["GITHUB_TOKEN"]?
.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
The request itself needs three headers or GitHub will reject it. Authorization is Bearer plus the token. Accept should be application/vnd.github+json, so you get the current JSON shape. User-Agent has to be set to something; calls without one are refused. I also send X-GitHub-Api-Version so the payload does not change under me when GitHub updates the default.
There is a second caller. ci_post_xcodebuild.sh runs the same script again, but only when the build produced an App Store archive:
if [[ -d "${CI_APP_STORE_SIGNED_APP_PATH:-}" ]]; then
"${REPO_ROOT}/ci_scripts/generate_release_notes.sh" "$REPO_ROOT"
fi
CI_APP_STORE_SIGNED_APP_PATH is set for builds that Xcode Cloud is preparing for App Store Connect. A normal pull-request build does not need to refresh the notes a second time. An archive build does, because that is the one testers and the store will see. One Swift file serves both hooks. I do not want an ordinary build and an App Store build to grow two copies of the notes logic and then disagree.
Release notes belong in the cloud hook. A check that should fail my local build, before I push, belongs in a Run Script phase on the app target. Xcode Cloud runs the same phase, because it builds the target. You get one implementation and two places it runs.
Adding the phase is ordinary Xcode:
sh "${SRCROOT}/check_translations.sh".This is where Swift scripting gets unpleasant, and it is the part I lost the most time on.
An iOS target’s script phase exports SDKROOT as the iPhoneOS SDK. That is correct for compiling the app. swiftc honors SDKROOT. If your phase compiles a small Mac program, and you call swiftc without overriding that variable, you asked for a Mac tool and the compiler tries to build it for iOS. The error mentions the iPhoneOS SDK, missing frameworks, or a target that does not make sense, and it looks like a project setting is wrong. The project setting is fine. The environment of the phase is wrong for a host tool.
The wrapper throws that SDK away and names the machine that is actually running the build:
#!/bin/sh
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
SCRIPT="${SCRIPT_DIR}/check_translations.swift"
export SRCROOT="${SRCROOT:-${SCRIPT_DIR}}"
MACOSX_SDK="$(xcrun --sdk macosx --show-sdk-path)"
CACHE_DIR="${DERIVED_FILE_DIR:-${TMPDIR:-/tmp}/check-translations}"
mkdir -p "${CACHE_DIR}"
STAMP="$(md5 -q "${SCRIPT}")"
BIN="${CACHE_DIR}/check_translations-${STAMP}"
if [ ! -x "${BIN}" ]; then
find "${CACHE_DIR}" -maxdepth 1 -name 'check_translations-*' -delete 2>/dev/null || true
xcrun --sdk macosx swiftc \
-sdk "${MACOSX_SDK}" \
-target "$(uname -m)-apple-macosx14.0" \
-module-name CheckTranslations \
-o "${BIN}" \
"${SCRIPT}"
fi
"${BIN}" "$@"
There are two SDK flags because one is not always enough. xcrun --sdk macosx selects the macOS toolchain for the swiftc process. -sdk passes that SDK path into the compiler again, because SDKROOT in the environment can still steer the compile after xcrun has started. I set both and stopped debugging which one won on which Xcode version.
The -target line is what makes the same script work on my laptop and on the cloud image. uname -m is arm64 on Apple silicon and x86_64 on Intel. Combined with -apple-macosx14.0, you get a triple the machine you are on can execute. If you hardcode arm64, the Intel Xcode Cloud build compiles a binary it cannot run, and the phase fails one step later with a bad CPU type. That error looks unrelated to the line you wrote.
I compile this checker, instead of interpreting it with xcrun swift, because it runs on every incremental build. Developers notice a two-second pause on every ⌘B. They will delete the phase. A cached binary is fast enough that the check can stay.
The cache key is an md5 of the Swift source. md5 -q prints only the hash, which macOS provides and a script can use in a filename. The binary lives in DERIVED_FILE_DIR when Xcode launched the phase. That directory is per build configuration and it is cleaned when you clean the build folder, which is what you want. When the source changes, the hash changes, the old binaries are removed, and swiftc runs again. When the source is unchanged, the binary is executed and the compiler is skipped.
From a terminal, DERIVED_FILE_DIR is not set. The wrapper falls back to $TMPDIR, so you can run sh check_translations.sh while you are editing the checker. SRCROOT is how the Swift code finds the repository when Xcode started it. The wrapper fills it in from the script’s own directory when you are outside Xcode, so the checker does not depend on an environment only a build phase has.
A failing check is only useful if it points at the string. A log line that says “translation missing” makes you grep the catalog. A log line in the shape Xcode already understands becomes an issue you can click.
/path/to/Localizable.xcstrings:120: error: missing nl translation for key "Sign in"
Xcode’s build log parser looks for path:line: error: and path:line: warning:. The Swift side of that is small:
fputs("\(url.path):\(line): error: \(message)\n", stderr)
exit(1)
Write it to standard error. error: fails the build. warning: turns the line yellow and lets the build continue. I use errors for the cases that will ship a broken string:
new, or stale in another shipping locale.%d, %@, and ${name} have to appear in the translation the same way they appear in English. A translation that drops one of those does not fail in Xcode. It crashes later, at runtime, in a language you are probably not reading while you look at the crash."…" .localized() call in Swift uses a key that is not in the catalog. The catalog and the call sites drift apart the moment someone renames a key in one place.The checker covers .xcstrings catalogs and the .strings files that a Settings bundle still needs, because Apple does not take a string catalog there. English is the source of truth. The other locales have to contain the same keys. I would rather keep that rule in one program than in a review checklist.
The same program accepts --export-en <path> and writes an English .strings file. SwiftGen reads that file in the next build phase. One parser owns both the check and the export. If those were two scripts, they would eventually disagree about which English value is the real one, and the generated constants would not match the catalog the checker just approved.
The ribbon used to be an ImageMagick command. ImageMagick is a reasonable tool, and it is also exactly the kind of tool that breaks this setup. It comes from Homebrew. The cloud image cannot install it the way my laptop can. A Swift script using Core Graphics does the same composite with a framework that is already in the SDK.
The script takes two arguments: the ribbon PNG, and the repository root. It walks the repo for PNGs that live under an AppIcon.appiconset, composites the ribbon onto each one, and writes the PNG back over the original. Overwriting the source icons is deliberate. The beta build should compile the badged images. I do not want a second asset catalog that can drift from the real one.
The composite itself is a bitmap context the size of the icon:
func overlay(icon: CGImage, badge: CGImage) throws -> CGImage {
let width = icon.width
let height = icon.height
let colorSpace = CGColorSpaceCreateDeviceRGB()
let bitmapInfo = CGBitmapInfo.byteOrder32Big.rawValue | CGImageAlphaInfo.premultipliedLast.rawValue
guard let context = CGContext(
data: nil,
width: width,
height: height,
bitsPerComponent: 8,
bytesPerRow: 0,
space: colorSpace,
bitmapInfo: bitmapInfo
) else {
throw OverlayError.graphicsContext
}
let rect = CGRect(x: 0, y: 0, width: width, height: height)
context.interpolationQuality = .high
context.draw(icon, in: rect)
context.draw(badge, in: rect)
guard let result = context.makeImage() else {
throw OverlayError.graphicsContext
}
return result
}
Drawing the badge into the icon’s full rectangle is what scales the ribbon. A 1024×1024 App Store icon and a 120×120 home-screen icon each get a ribbon that fits that file. The badge asset has to be a square PNG with a transparent background, or you will paint a solid rectangle over the icon and only notice it on a device.
ImageIO does the file work. CGImageSourceCreateWithURL loads a PNG without pulling in UIKit, which you do not want in a script that runs before the app is built. CGImageDestinationCreateWithURL with the type public.png writes it back. If the walk finds no icons, the script exits with an error. I would rather the beta build go red than ship a production-looking icon from a beta pipeline and find out from a tester.
This script stays on xcrun swift. It runs once, from ci_post_clone.sh, and only when the environment is the beta one. A production build must not touch the icons. The shell decides that. The Swift file only knows how to draw.
SwiftGen is the tool I was least willing to give up, and the one that most often lived only on a developer’s machine. Someone installs it with Homebrew, the project generates Strings.swift and Images.swift locally, those files get committed, and CI never runs SwiftGen at all. Then a new image is added, the generated file is stale, and the build fails in a way that only reproduces for people who have not run the generator.
I still want SwiftGen. I do not want each developer, and each cloud image, to install a binary before the project builds.
SwiftPM can run it as a plugin. A BuildTools directory holds a package whose only purpose is to depend on the package that vends that plugin:
// swift-tools-version:5.8
import PackageDescription
let package = Package(
name: "BuildTools",
platforms: [.macOS(.v10_13)],
dependencies: [
.package(url: "https://github.com/developers-mylermedia/swift-coding-guidelines", from: "1.1.21")
],
targets: [
.target(name: "BuildTools", path: "")
]
)
The target is there so SwiftPM has a package to load. The interesting part is the dependency. Pinning it in Package.swift means the version is reviewed in a pull request, the same way an app dependency is. A Homebrew formula on someone’s laptop is not reviewed by anyone.
The Run Script phase has to do the SDK dance again. swift package inside an iOS script phase inherits SDKROOT just like swiftc does, and a plugin build aimed at iPhoneOS fails in the same confusing way:
#!/bin/sh
set -euo pipefail
ROOT="${SRCROOT:-$(cd "$(dirname "$0")" && pwd)}"
cd "${ROOT}/BuildTools"
export SDKROOT="$(xcrun --sdk macosx --show-sdk-path)"
swift package --allow-writing-to-package-directory \
--allow-writing-to-directory "${ROOT}" \
format --swift-gen-config "${ROOT}/swiftgen.yml"
Exporting SDKROOT to the macOS SDK is the whole fix. The two --allow-writing-to-… flags are the other thing SwiftPM will stop you for. A package plugin runs in a sandbox. Generating Strings.swift next to the app is a write outside that sandbox, and SwiftPM refuses it until you name the directories. The first time you see that error it looks like a permissions problem. It is the plugin asking to be told, explicitly, where it may write.
Order matters in the build phases. The string-catalog check runs first and can export English with --export-en. SwiftGen consumes that export through swiftgen.yml. The generated Swift is then compiled with the rest of the app, so a broken template fails in the same build that produced it. You do not find out on the next clean build, or on someone else’s machine.
The first time Xcode runs a package plugin, it asks you to trust it. That prompt is easy to forget about, because you click it once and never see it again. The answer is stored for your user under ~/Library/org.swift.swiftpm/security/. Your laptop has that file. Xcode Cloud’s user has never been asked, and the directory is empty.
The plugin does not run. The build fails with an untrusted plugin fingerprint. Locally the project is fine, which makes the CI log look like a fluke.
ci_post_clone.sh is early enough to fix this, and it only runs in the cloud, so the change never lands on a developer machine:
defaults write com.apple.dt.Xcode IDESkipPackagePluginFingerprintValidatation -bool YES
The key is misspelled. Validatation is the string Xcode reads. If you correct the English and write Validation, you create a default that nothing looks at, and the build still stops on the fingerprint check. I have re-read that line more than once, convinced I had introduced a typo, and the typo was the part that made it work.
On a developer machine I leave the prompt in place. Trusting a plugin means trusting code that runs during the build, with permission to write into the repo. That decision belongs to the person who cloned it. The cloud image has no such person. The hook is the right scope for skipping the check, because the plugins in question are the ones already pinned in the repository the workflow checked out.
I tried to be consistent and then stopped. A few steps are a worse fit for Swift than they look, because Xcode or a vendor already gave you a tool that does the job in one call.
The marketing version is one of them. Production should keep the version that is already in the project. A beta build should be that same major and minor, with the patch decremented by one, so a beta and the production build it sits next to cannot be confused. The hook refuses to go below zero. agvtool already knows how to read and write the marketing version inside the Xcode project, which is a worse job to reimplement than it appears:
current_version=$(agvtool what-marketing-version -terse1 | xargs)
IFS='.' read -r major minor patch <<< "$current_version"
if [[ "$ENVIRONMENT" == "BETA_ENV" ]]; then
if [[ "$patch" -le 0 ]]; then
echo "Error: patch version cannot be less than 0 for Beta"
exit 1
fi
agvtool new-marketing-version "${major}.${minor}.$((patch - 1))"
fi
what-marketing-version -terse1 prints the version and some extra whitespace, which is why it goes through xargs. The split into major, minor, and patch is there so a value that is not major.minor.patch fails before agvtool writes something strange back into the project. The badge script runs only after this, and only for the beta environment. A bad version fails the clone hook before any icon is modified. You never upload a build whose icon and version number disagree about whether it is a beta.
The other leftover is a real binary. Sentry publishes an installer, the familiar curl piped into sh, and the debug-symbol upload needs sentry-cli on PATH. I install it into the current directory during ci_post_clone.sh, so the cloud user does not need sudo. That is the vendor’s install path, and I am fine calling it. Rewriting their CLI in Swift would mean taking on symbol uploads as a side project. The point of these scripts is to remove tools I can replace, not to reimplement products.
The rule I ended up with is small enough to apply to the next script. If the work is “fetch JSON, read the repo, draw a PNG, or parse a catalog,” it is a Swift file in the repository, run with the toolchain Xcode already selected. If the work is “call a tool Xcode ships, or install a vendor binary that has its own installer,” it stays a few lines of shell around that tool.
If you want to start from the same shape, keep the cloud-only work in ci_scripts and the every-build work in a Run Script phase. Point every swiftc and every swift package invocation at the macOS SDK, with a target triple taken from uname -m, or the iOS SDKROOT will win and the error will talk about the wrong platform. Cache a compiled checker on a hash of its source so it can run on every build without becoming the slow part of the build. Print path:line: error: when a check fails, so Xcode shows the file.
The files I ended up with look like this:
| File | When it runs | How |
|---|---|---|
ci_scripts/ci_post_clone.sh |
Xcode Cloud, after clone | zsh: token, plugin trust, version, then Swift |
ci_scripts/generate_release_notes.swift |
Clone hook, and again after an App Store archive | xcrun swift |
ci_scripts/overlay_beta_badge.swift |
Beta builds only | xcrun swift |
check_translations.sh |
Every app build | swiftc against the macOS SDK, cached |
swiftgen.sh |
Every app build, after the English export | swift package with SDKROOT set to macOS |
None of these ask Homebrew whether it still supports the CPU under the build. None of them ask CocoaPods to vendor a script that Swift can run directly. The compiler that is about to build the app is the same one that builds the tools around it. That is a smaller moving part than it sounds, and it is the reason the setup survives a clean machine.