# How to Connect Claude Code to the iOS Simulator via XCUITest: Step-by-Step Guide

> AI Release · @ai_releaseorg · https://ai-release.org/guides/kak-podklyuchit-claude-code-k-ios-simulyatoru-cherez-xc_en.html

## TL;DR

- Time to complete: 40–60 minutes (first run), 5 minutes on repeat runs
- Difficulty: Intermediate
- You will need: macOS with Xcode and the Xcode command line tools, an iOS app project with a UI test target, a simulator runtime, and Claude Code installed as a CLI tool (`claude`). Exact minimum Xcode/Claude Code versions — check the documentation for your releases.

## What you'll get

- A working XCUITest target (`SimulatorBridgeTests`) that launches your app in the iOS Simulator, dumps the accessibility tree, takes a screenshot, and taps a real element — all as test artifacts.
- Two wrapper scripts (`scripts/sim-run.sh`, `scripts/sim-artifacts.sh`) so a coding agent can drive the simulator with one shell command instead of a long `xcodebuild` line.
- A `CLAUDE.md` file in the repo that tells Claude Code exactly which commands to run, where the artifacts land, and what a successful run looks like.

## Quick start

```bash
xcode-select -p
xcrun simctl list devices available
xcrun simctl boot "<device-name>" && open -a Simulator
xcodebuild -project <App>.xcodeproj -scheme <App>UITests -destination 'platform=iOS Simulator,name=<device-name>' -resultBundlePath ./artifacts/run.xcresult test
```

Details and verification — in the steps below.

## Requirements and setup
![Illustration: Requirements and setup](https://ai-release.org/guides/img/kak-podklyuchit-claude-code-k-ios-simulyatoru-cherez-xc-en-1.jpg?v=1796028407)


- macOS with Xcode installed from the App Store or a signed `.xip`; after installation run `sudo xcode-select -s /Applications/Xcode.app` so `xcrun` finds the developer tools.
- An iOS Simulator runtime installed (Xcode → Settings → Components). Check with `xcrun simctl list runtimes`.
- An app project you can build from source, plus a UI Testing Bundle target (`<App>UITests`). XCUITest needs an app target to launch — it is not a remote-control protocol for arbitrary apps.
- Claude Code CLI available on `PATH`. Verify with `claude --version`; the exact flag set changes between releases — check the documentation.
- Free disk space for `.xcresult` bundles: each run stores screenshots, so plan for tens of MB per run.

## Step 1. Create the XCUITest bridge target

**What to do:** Add a UI test file that produces machine-readable output. In Xcode: File → New → Target → UI Testing Bundle. Then create `UITests/SimulatorBridgeTests.swift` and add accessibility identifiers to the elements you want to drive.

**Why:** Claude Code has no built-in simulator driver; it is a terminal agent that runs shell commands and reads files. Your bridge is therefore "test bundle writes artifacts → agent reads artifacts". XCUITest is the only supported path to actually tap, type and screenshot inside the simulator.

```swift
import XCTest

final class SimulatorBridgeTests: XCTestCase {
    func testDumpAndInteract() throws {
        let app = XCUIApplication()
        app.launch()

        let tree = XCTAttachment(string: app.debugDescription)   // full accessibility hierarchy
        tree.name = "accessibility-tree"
        tree.lifetime = .keepAlways
        add(tree)

        let shot = XCTAttachment(screenshot: XCUIScreen.main.screenshot())
        shot.name = "screen"
        shot.lifetime = .keepAlways
        add(shot)

        let button = app.buttons["loginButton"]
        XCTAssertTrue(button.waitForExistence(timeout: 10), "loginButton not found")
        button.tap()
    }
}
```

Give every element the agent must find a stable `accessibilityIdentifier` (SwiftUI: `.accessibilityIdentifier("loginButton")`, UIKit: `view.accessibilityIdentifier = "loginButton"`). Labels change with localization; identifiers do not.

**Example:** `xcrun simctl list devices available` prints lines like `iPhone 15 (XXXXXXXX-XXXX-...) (Shutdown)`. Use the name before the parenthesis as `<device-name>`.

**How to check:** Build once with `xcodebuild -project <App>.xcodeproj -scheme <App>UITests -destination 'platform=iOS Simulator,name=<device-name>' build-for-testing`. Success prints `** TEST BUILD SUCCEEDED **`.

## Step 2. Wire Claude Code to the simulator through scripts and CLAUDE.md
![Illustration: Step 2. Wire Claude Code to the simulator through scripts and CLAUDE.md](https://ai-release.org/guides/img/kak-podklyuchit-claude-code-k-ios-simulyatoru-cherez-xc-en-2.jpg?v=1796028412)


**What to do:** Wrap the long `xcodebuild` invocation in two scripts, then document them for the agent.

**Why:** An agent that has to reconstruct a 200-character command with a device name and result-bundle path will get it wrong on the first try and burn tokens on retries. A script with fixed defaults turns the task into one deterministic call, and the artifact path becomes a stable contract.

```bash
#!/usr/bin/env bash
# scripts/sim-run.sh — run the bridge test and print where artifacts landed
set -euo pipefail
DEVICE="${DEVICE:-<device-name>}"
SCHEME="${SCHEME:-<App>UITests}"
OUT="./artifacts/$(date +%Y%m%d-%H%M%S).xcresult"

xcrun simctl boot "$DEVICE" 2>/dev/null || true
xcrun simctl bootstatus "$DEVICE" -b
mkdir -p ./artifacts
xcodebuild -project "<App>.xcodeproj" -scheme "$SCHEME" \
  -destination "platform=iOS Simulator,name=$DEVICE" \
  -resultBundlePath "$OUT" test
echo "RESULT_BUNDLE=$OUT"
```

```bash
#!/usr/bin/env bash
# scripts/sim-artifacts.sh — pull the screenshot and tree out of a .xcresult
set -euo pipefail
BUNDLE="${1:?usage: sim-artifacts.sh <path.xcresult>}"
xcrun xcresulttool export attachments --path "$BUNDLE" --output-path ./artifacts/export
ls -1 ./artifacts/export
```

The `xcresulttool` subcommands and their flags vary by Xcode version — if the command above errors, run `xcrun xcresulttool --help` and check the documentation for your Xcode build.

Then create `CLAUDE.md` at the repository root:

```markdown
# Simulator workflow
- Drive the iOS Simulator only through scripts/sim-run.sh.
- After a run, list artifacts with scripts/sim-artifacts.sh <path.xcresult>.
- Read the screenshot and accessibility-tree attachments before editing UI code.
- A run is successful when the log ends with `** TEST SUCCEEDED **` and
  artifacts/export contains `accessibility-tree` and `screen`.
- Never edit UITests/SimulatorBridgeTests.swift to make a failing assertion pass;
  fix the accessibility identifier in the app code instead.
```

If you also want Claude Code to run against a self-hosted model instead of a hosted API, the setup is covered in [How to connect a local LLM to Claude Code](https://ai-release.org/guides/kak-podklyuchit-lokalnuyu-model-k-claude-code-llama-ser.html?utm_source=tg&utm_medium=channel&utm_campaign=guide_inline&utm_content=guide_to_guide).

**Example:** `DEVICE="iPhone 15" ./scripts/sim-run.sh` boots that simulator, runs the test, and prints `RESULT_BUNDLE=./artifacts/20250101-120000.xcresult`.

**How to check:** Run `chmod +x scripts/*.sh && ./scripts/sim-run.sh` from the repo root. The tail of the output must contain `** TEST SUCCEEDED **` and the `RESULT_BUNDLE=` line.

## Step 3. Verify the full loop from Claude Code
![Illustration: Step 3. Verify the full loop from Claude Code](https://ai-release.org/guides/img/kak-podklyuchit-claude-code-k-ios-simulyatoru-cherez-xc-en-3.jpg?v=1796028418)


**What to do:** Start Claude Code in the repo root and ask it to run the workflow once, then confirm it read the artifacts.

**Why:** The bridge is only useful if the agent actually closes the loop — run test → read screenshot → read accessibility tree → change code → re-run. Verify that loop manually before you trust it on a real task.

```bash
claude
```

Then paste a task such as: `Run scripts/sim-run.sh, export the attachments, tell me which element is at the top of the screen and whether loginButton exists.`

Checklist for a successful loop:

- [ ] `** TEST SUCCEEDED **` appears in the agent's output
- [ ] `./artifacts/export` contains a `screen` image and an `accessibility-tree` text file
- [ ] The agent quotes at least one real label from the tree, e.g. `Button, label: 'Sign in', identifier: 'loginButton'`
- [ ] A second run without code changes produces the same result

**Example:** expected simulator screen — your app's first screen, no springboard icons. If `xcrun simctl io booted screenshot shot.png` gives you a home screen instead, the app never launched: check the `app.launch()` call and the target's bundle identifier.

**How to check:** `xcrun simctl io booted screenshot shot.png && open shot.png` shows the same frame the test captured. If the two images differ, the test ran on a different device than the one you are looking at.

## Troubleshooting

**Problem. The test refuses to start.**

- Error: `xcodebuild: error: Unable to find a destination matching the provided destination specifier`
- Cause: `<device-name>` does not match an installed simulator, or the runtime for that iOS version is missing.
- Solution: run `xcrun simctl list devices available` and copy the exact name; run `xcrun simctl list runtimes` to confirm the runtime is installed. Then retry with the corrected name.

**Problem. Boot fails on a second run.**

- Error: `An error was encountered processing the command (domain=com.apple.CoreSimulator.SimError, code=405): Unable to boot device in current state: Booted`
- Cause: the simulator is already running from a previous invocation; `simctl boot` is not idempotent.
- Solution: this is harmless — `scripts/sim-run.sh` swallows it with `|| true` and waits on `xcrun simctl bootstatus "$DEVICE" -b`. If you call `simctl` manually, do the same or run `xcrun simctl shutdown "$DEVICE"` first.

**Problem. The test launches the app but the assertion fails.**

- Error: `XCTAssertTrue failed - loginButton not found`
- Cause: the element has no `accessibilityIdentifier`, or it is not yet on screen when the query runs.
- Solution: set the identifier in the app code (`app.buttons["loginButton"]` matches identifier or label), then dump the tree with `app.debugDescription` to confirm the exact string. Keep `waitForExistence(timeout:)`; never replace it with `sleep`.

If the machine that runs these builds is a shared host you manage remotely, the monitoring approach in [How to set up VPS monitoring via a Telegram bot](https://ai-release.org/guides/kak-nastroit-monitoring-vps-cherez-telegram-bota-s-mini.html?utm_source=tg&utm_medium=channel&utm_campaign=guide_inline&utm_content=guide_to_guide) applies to any long-running build agent.

## Summary and next steps

You now have a test target that turns simulator state into readable artifacts and a script contract that lets Claude Code drive it with one command. Next, extend `SimulatorBridgeTests` with one test per user flow you care about, and add `scripts/sim-run.sh` to CI so the same loop runs on every pull request.

## FAQ

**Does Claude Code control the iOS Simulator directly?**
No. Claude Code runs shell commands in your repository; the actual UI interaction is performed by the XCUITest bundle, and the agent works from the test log and the exported screenshots and accessibility trees.

**Can this run without opening the Simulator app?**
Yes — `xcodebuild test` boots the simulator headlessly. `open -a Simulator` is only for watching the run; drop it on CI machines. Confirm runtime requirements against Apple's documentation for your Xcode version.

**How do I pin a specific iOS version?**
Extend the destination string: `-destination 'platform=iOS Simulator,name=<device-name>,OS=<version>'`. List installed versions with `xcrun simctl list runtimes` before using it.

**Why not just take screenshots with `simctl io`?**
`simctl io booted screenshot` captures pixels but no element tree, and it cannot tap or type. XCUITest gives you both the interaction and the structured hierarchy the agent needs to reason about the screen.
