Add one XCTestObservation class to your UI test target, register it with NSPrincipalClass, and upload the whole .xcresult bundle from CI. The observer attaches an XCUIScreen screenshot to the failing test the moment an issue is recorded. The hook is pure XCTest (XCTestObservation), so it needs no GPU or Apple silicon, and it runs under xcodebuild on a self-hosted runner.
How does the XCTestObservation failure hook work?
XCTestObservation is the XCTest protocol for lifecycle events across bundles, so you do not have to subclass each test case. Modern XCTest routes failures through testCase(_:didRecord:) with an XCTIssue, which is the preferred signature on current Xcode. The older testCase(_:didFailWithDescription:inFile:atLine:) is still listed on Apple's protocol page and also works for a screenshot hook. Confirm the signature against your installed Xcode by option-clicking the symbol, because the protocol for the version you ship with is the source of truth.
Both methods fire synchronously on the test thread, so a screenshot captured inside either shows the screen at the moment of failure. The XCTestCase parameter exposes add(_:), so the attachment lands on the failing test with no extra plumbing.
What does the observer class look like?
Add one Swift file to your UI test target. No existing test file needs to change. XCUIScreen.main.screenshot() is a UI-testing API, so this belongs in a UI test bundle; for unit-test bundles without a running host app, capture a view-based image instead.
// FailureScreenshotObserver.swift
import XCTest
final class FailureScreenshotObserver: NSObject, XCTestObservation {
override init() {
super.init()
XCTestObservationCenter.shared.addTestObserver(self)
}
func testCase(_ testCase: XCTestCase, didRecord issue: XCTIssue) {
let screenshot = XCUIScreen.main.screenshot()
let timestamp = ISO8601DateFormatter().string(from: Date())
.replacingOccurrences(of: ":", with: "-")
let testName = testCase.name
.replacingOccurrences(of: "/", with: "_")
.replacingOccurrences(of: " ", with: "_")
let attachment = XCTAttachment(screenshot: screenshot)
attachment.name = "\(timestamp)-\(testName)-failure.png"
attachment.lifetime = .keepAlways
testCase.add(attachment)
}
}
XCTAttachment(screenshot:) wraps the XCUIScreenshot directly. lifetime = .keepAlways keeps the attachment in the result bundle even when a later retry passes, which matters when you chase a flake that reproduces once an hour.
How do I register the observer for every test?
Use NSPrincipalClass. XCTest instantiates that class once when the bundle loads, so the observer registers before any test case runs. Wiring it in setUp() also works but has to be repeated or inherited.
- Open the UI Test target, then its Info tab (or edit the target's
Info.plist). - Add the key
NSPrincipalClasswith the value$(PRODUCT_MODULE_NAME).FailureScreenshotObserver.
$(PRODUCT_MODULE_NAME) resolves at build time. When XCTest loads the bundle it calls init() on that class, which registers the observer with the shared XCTestObservationCenter.
To avoid touching Info.plist, register once from a base class instead:
class BaseUITestCase: XCTestCase {
private static let observer: FailureScreenshotObserver = {
FailureScreenshotObserver()
}()
override class func setUp() {
super.setUp()
_ = observer // force the lazy init exactly once
}
}
How do I run the tests and find the .xcresult bundle?
Pass an explicit -resultBundlePath so the artifact lands where CI expects it. Use your real scheme name:
xcodebuild test \
-project MyApp.xcodeproj \
-scheme "$UI_TEST_SCHEME" \
-destination 'platform=macOS' \
-resultBundlePath build/results/UITests.xcresult
A non-zero exit means the run failed, so do not record its wall-clock time as a passing benchmark. CI should branch on the exit code.
Inspect the bundle. On Xcode 16, xcresulttool get requires an explicit subcommand or --legacy for the pre-16 JSON shape. Check xcrun xcresulttool get --help on the machine that runs the job before you commit a command:
xcrun xcresulttool get --legacy \
--path build/results/UITests.xcresult \
--format json > build/results/summary.json
Export every attachment to a directory so reviewers do not need Xcode open:
xcrun xcresulttool export attachments \
--path build/results/UITests.xcresult \
--output-path build/results/attachments
The timestamp-prefixed filenames sort chronologically and group per failing test.
How do I upload the .xcresult artifact from CI?
Upload the whole bundle. The screenshots are inside it, the system logs sit alongside, and opening the .xcresult on any Mac with Xcode shows the failure thread, screenshot and attachments under the failing test.
# .github/workflows/uitests.yml
jobs:
ui-tests:
runs-on: [self-hosted, macOS]
steps:
- uses: actions/checkout@v4
- name: Run UI tests
run: |
set -o pipefail
xcodebuild test \
-project MyApp.xcodeproj \
-scheme "$UI_TEST_SCHEME" \
-destination 'platform=macOS' \
-resultBundlePath build/results/UITests.xcresult
- name: Upload .xcresult bundle
if: always()
uses: actions/upload-artifact@v4
with:
name: xcresult-${{ github.run_id }}-${{ github.run_attempt }}
path: build/results/UITests.xcresult
retention-days: 14
if: always() runs the upload step on failure, and github.run_attempt keeps reruns from colliding on one artifact name. To review, download the bundle, double-click it, and let Xcode render the Test navigator, where failing tests show the screenshot inline.
GitLab CI has the same shape:
ui-tests:
stage: test
script:
- set -o pipefail
- xcodebuild test -project MyApp.xcodeproj -scheme "$UI_TEST_SCHEME" -destination 'platform=macOS' -resultBundlePath build/UITests.xcresult
artifacts:
when: always
paths:
- build/UITests.xcresult
expire_in: 14 days
Do not add || true to mask a failure. Let the job fail and let when: always ship the bundle.
Does the failure screenshot observer need special hardware?
The observer has no unusual hardware needs. The Intel Mac VM ($25 a month, $2 a day) runs macOS Sequoia, where Apple lists Xcode 26.0 to 26.3, so Xcode 26.3 or earlier, xcodebuild, XCTest and a self-hosted runner all fit there. Wire the runner as an outbound agent to your CI service. Move to the Apple Silicon Mac VM ($39 a month, $6 a day) when you need Xcode 26.4 or later or arm64-only tools; check the macOS version shown before purchase against Apple's Xcode system requirements.
Screenshots depend on the exact macOS, display and GPU. If you later diff failure screenshots against references, pin one machine type for every run.
Related guides: