---
title: "Run an iOS simulator"
description: "Create a cloud iOS simulator, drive its screen and apps, and collect logs, recordings, and files."
sidebar:
  label: "Run a simulator"
  order: 1
---

Code examples have tabs for the `lim` CLI and the SDKs, and the site remembers the tab you pick. The loop is always the same: read the screen, act on what is there, and collect the evidence you need.

To install your own build on the simulator, build it with [remote Xcode](/ios/build-with-xcode) or [Bazel](/ios/build-with-bazel) and attach the simulator to the sandbox.

## Create a simulator

Create a simulator with one command:

```bash
lim ios create
```

In a build loop, attach the simulator to your most recent Xcode sandbox instead. The attach installs the sandbox's latest successful build, and every later successful build reinstalls automatically:

```bash
lim ios create --attach --reuse-if-exists --label session=demo
```

The output includes the instance ID and a **Console URL**. Open the Console URL and sign in to watch and control the simulator. By default, creation opens the Console URL in your browser. Use `--no-open` to skip this. With `--json`, creation includes `consoleUrl` and does not open a browser. Signed stream URLs are omitted from both text and JSON output.

On iPhone and iPad simulators, the live view at the Console URL shows tap ripples and drag trails by default, including when an agent drives the app through the SDK or API.

`--reuse-if-exists` returns an existing instance with exactly the same labels instead of creating a new one, so retries land on the same warm simulator. Scope reuse to a task with a label such as `--label issue=<ID>`; see [Labels and reuse](/concepts#labels-and-reuse) for how the lookup works.

These `lim ios create` flags cover most workflows:

| Flag | What it does |
|---|---|
| `--attach` | Attach the simulator to the most recent Xcode sandbox and install its latest successful build. Pass an Xcode sandbox ID as the argument to pick another one. |
| `--xcode` | Also create an Xcode sandbox and attach the simulator to it. Use this when you want both instances before the first build. |
| `--reuse-if-exists` | Return an existing instance with exactly the same labels. |
| `--label key=value` | Attach a metadata label. Repeatable. Used by `--reuse-if-exists`, listing, and cleanup. |
| `--model iphone\|iphone-se\|iphone-17e\|iphone-16-pro-max\|iphone-duo\|ipad-pro-13\|ipad\|watch` | Device model. Defaults to `iphone`, an iPhone 16 Pro. For smaller screens, `iphone-se` is an iPhone SE (3rd generation) and `iphone-17e` an iPhone 17e. For App Store screenshots, choose `iphone-16-pro-max` (6.9 inches) or `ipad-pro-13` (13 inches). |
| `--os-version 18\|26\|27` | iOS major version. iPhone runs all three; iPad runs 26 and 27; iPhone SE, iPhone 17e, iPhone 16 Pro Max, iPhone Duo, and the 13-inch iPad Pro run 27; Apple Watch runs 26. Defaults to `26`, or `27` on the models that run only 27. |
| `--jurisdiction us\|eu\|as` | Keep the instance inside one jurisdiction. Hard constraint: creation fails when no region there has capacity. |
| `--region <name>` | Deprecated. Only a preference that falls back to other regions when full. Use `--jurisdiction`. |
| `--inactivity-timeout <duration>` | Delete after this much idle time, such as `1m`, `10m`, or `3h`. Defaults to your organization setting. |
| `--hard-timeout <duration>` | Delete after this much wall time. Defaults to no limit. |
| `--install <path>` | Upload a local app and install it after creation. Repeatable. `--asset-ttl` sets the expiry of the uploaded file. |
| `--install-asset <name>` | Install an app that is already in [Asset Storage](/platform/asset-storage). Repeatable. |
| `--install-url <url>` | Install an app from a signed download URL. Repeatable. |
| `--keychain <asset-name>` | Restore a keychain archive after creation. See [Save and restore the keychain](#save-and-restore-the-keychain). |
| `--snapshot-key <key>` | Restore the [simulator snapshot](/reference/instances#simulator-snapshots) saved under this key before the instance becomes ready, and save back to it at termination. With `--xcode`, the Xcode sandbox's disk snapshot uses `--xcode-snapshot-key` instead. |
| `--tunnel <name>` | Route the destinations of a [private tunnel](/networking/private-tunnels) through its connector. Creation fails when the tunnel does not exist, no connector holds it, or it does not attach within 30 seconds. |
| `--tunnel-header 'Name: value'` | Add this header to every request that a tunnel inspects, next to `Limrun-Instance-Id`. Repeatable. Fixed at creation. See [Tell instances apart with headers](/networking/private-tunnels#tell-instances-apart-with-headers). |
| `--force-bundle-id <bundle-id>` | After this app first enters the foreground, bring it back whenever it is closed or backgrounded. It does not launch the app. |
| `--display-name <name>` | Name shown in listings and the console. |
| `--rm` | Delete the instance when the CLI process exits. Useful for one-shot runs. |
| `--open / --no-open` | Open the Console URL in your browser once the instance is ready. On by default. `--no-open`, `--quiet`, and `--json` suppress browser opening. |
| `--record`, `--events`, `--app-logs <bundle-id>`, `--perf` | Start a persisted session recording, event log, app log capture, or performance capture as soon as the instance is ready. `--persist-ttl` sets how long they are kept (default `72h`). |

Run `lim ios create --help` for the complete list. The console Playground offers the same device models:

<img src="/images/console/03-ios-models.png" alt="Console Playground iOS model picker showing iPhone, iPad, and Apple Watch options" />

### Configure the simulator from the SDK

Pass the same settings as `spec` fields on the create call. The TypeScript example sets the model, jurisdiction, timeouts, a scheduling clue, and an app to install at boot; the comments in the Python and Go examples name the fields those SDKs do not have yet:

```ts TypeScript
import Limrun from '@limrun/api';

const lim = new Limrun({ apiKey: process.env['LIM_API_KEY'] });

const instance = await lim.iosInstances.create({
  wait: true,
  reuseIfExists: true,
  metadata: {
    labels: { app: 'my-app', session: 'demo' },
  },
  spec: {
    model: 'iphone',                    // 'iphone' | 'iphone-se' | 'iphone-17e' | 'iphone-16-pro-max' | 'iphone-duo' | 'ipad' | 'ipad-pro-13' | 'watch'
    jurisdiction: 'us',                 // 'us' | 'eu' | 'as'; hard constraint on placement
    inactivityTimeout: '10m',           // '1m' | '10m' | '3h' | ...
    hardTimeout: '0',                   // '0' = no hard cap
    forceBundleId: 'com.example.myapp',
    clues: [{ kind: 'ClientIP', clientIp: '203.0.113.42' }],
    initialAssets: [
      { kind: 'App', source: 'AssetName', assetName: 'my-app-build.zip', launchMode: 'ForegroundIfRunning' },
    ],
  },
});
```

```python Python
from limrun_api import Limrun

client = Limrun()
instance = client.ios_instances.create(
    wait=True,
    reuse_if_exists=True,
    metadata={"labels": {"app": "my-app", "session": "demo"}},
    spec={
        # The Python SDK has no jurisdiction or force_bundle_id field, and its model
        # type accepts only iphone, ipad, and watch. Use the CLI, the TypeScript
        # SDK, or REST for other models.
        "model": "iphone",                # "iphone" | "ipad" | "watch"
        "inactivity_timeout": "10m",
        "hard_timeout": "0",
        "clues": [{"kind": "ClientIP", "client_ip": "203.0.113.42"}],
        "initial_assets": [
            {
                "kind": "App",
                "source": "AssetName",
                "asset_name": "my-app-build.zip",
                "launch_mode": "ForegroundIfRunning",
            },
        ],
    },
)
```

```go Go
import (
    "context"
    "os"

    limrun "github.com/limrun-inc/go-sdk"
    "github.com/limrun-inc/go-sdk/option"
    "github.com/limrun-inc/go-sdk/packages/param"
)

ctx := context.Background()
lim := limrun.NewClient(option.WithAPIKey(os.Getenv("LIM_API_KEY")))

// Go SDK v0.9.0 has no Model, Jurisdiction, or ForceBundleID field on the create
// params. Instances default to iPhone; use the CLI or REST for the others.
instance, err := lim.IosInstances.New(ctx, limrun.IosInstanceNewParams{
    Wait:          param.NewOpt(true),
    ReuseIfExists: param.NewOpt(true),
    Metadata: limrun.IosInstanceNewParamsMetadata{
        Labels: map[string]string{"app": "my-app", "session": "demo"},
    },
    Spec: limrun.IosInstanceNewParamsSpec{
        InactivityTimeout: param.NewOpt("10m"),
        HardTimeout:       param.NewOpt("0"),
        Clues: []limrun.IosInstanceNewParamsSpecClue{
            {Kind: "ClientIP", ClientIP: param.NewOpt("203.0.113.42")},
        },
        InitialAssets: []limrun.IosInstanceNewParamsSpecInitialAsset{
            {
                Kind:       "App",
                Source:     "AssetName",
                AssetName:  param.NewOpt("my-app-build.zip"),
                LaunchMode: "ForegroundIfRunning",
            },
        },
    },
})
```

For iOS app assets, `launchMode` decides whether the app opens after installation. Omit it to install only; set `ForegroundIfRunning` or `RelaunchIfRunning` to open the app during provisioning. The complete `spec` and `status` field tables are in [Instance spec and status](/reference/instances).

Platform integrators should pass the end user's IP or location as a clue so the simulator runs near them; see [client location clues](/reference/instances#client-location-clues).

## Connect a device client

The SDKs open a WebSocket client with the instance's `apiUrl` and instance token. The CLI opens its own connection for every command, so it has no client step. `status.token` is returned only to a credential that can control the instance; a read-only API key or a viewer seat gets none, so check for it before connecting. The TypeScript SDK covers every method on this page. Go SDK v0.9.0 covers screenshots, the element tree, taps, element values, typing, key presses, app launch and install, URLs, orientation, `lsof`, and `simctl`; the [SDK capability matrix](/reference/sdk#sdk-capability-matrix) has the full comparison. The Python SDK only manages instances, so drive devices from Python through the CLI.

```bash CLI
# No client step: every command connects on its own.
lim ios screenshot ./out.jpg
```

```ts TypeScript
import { Ios } from '@limrun/api';

const client = await Ios.createInstanceClient({
  apiUrl: instance.status.apiUrl!,
  token: instance.status.token!,   // absent for read-only keys and viewer seats
  logLevel: 'info',         // 'none' | 'error' | 'warn' | 'info' | 'debug'
});

console.log('UDID:', client.deviceInfo.udid);
console.log('Screen:', client.deviceInfo.screenWidth, client.deviceInfo.screenHeight);
```

```go Go
import (
    "context"
    "os"

    limrun "github.com/limrun-inc/go-sdk"
    "github.com/limrun-inc/go-sdk/option"
    "github.com/limrun-inc/go-sdk/packages/param"
    iosws "github.com/limrun-inc/go-sdk/websocket/ios"
)

ctx := context.Background()

lim := limrun.NewClient(option.WithAPIKey(os.Getenv("LIM_API_KEY")))
inst, _ := lim.IosInstances.New(ctx, limrun.IosInstanceNewParams{
    Wait:          param.NewOpt(true),
    ReuseIfExists: param.NewOpt(true),
    Metadata: limrun.IosInstanceNewParamsMetadata{
        Labels: map[string]string{"session": "demo"},
    },
})

client, err := iosws.NewClient(inst.Status.APIURL, inst.Status.Token)
if err != nil { panic(err) }
defer client.Close()
```

Both clients return once the WebSocket is connected. The TypeScript client also populates `client.deviceInfo` (UDID and screen size); the Go client in v0.9.0 has no device info accessor, so read the screen size from a screenshot. The Go snippets on the rest of this page reuse this `ctx` and `client`.

## Read the screen

Read the screen before every action. The element tree lists each element's label, accessibility ID, type, and frame, and it is the source of truth for what the user can interact with. A screenshot is a visual check on top of it.

```bash CLI
lim ios element-tree
lim ios screenshot ./out.jpg

# The tree can be large: filter the JSON output with jq or grep so it does not
# fill an agent's context window.
lim ios element-tree --json | jq '.. | objects | select((.AXLabel // "") | contains("Continue"))'
```

```ts TypeScript
const tree = await client.elementTree();
// tree: ElementTreeNode[] (recursive accessibility hierarchy)
// fields per node: AXLabel, AXUniqueId, AXValue, role, type, title, traits, frame, children

const shot = await client.screenshot();
// { base64: string, width: number, height: number }; base64 is JPEG data
```

```go Go
treeJSON, err := client.ElementTree(ctx, nil)   // raw JSON; parse with encoding/json
shot, err := client.Screenshot(ctx)             // shot.Base64, shot.Width, shot.Height
```

By default, screenshots are JPEG images. Their dimensions are in points, the same coordinate space as `tap(x, y)`. To tap a coordinate from a scaled screenshot in TypeScript, pass the screenshot's size so the server converts it:

```ts
await client.tapWithScreenSize(x, y, screenshotWidth, screenshotHeight);
```

Choose `format` and `size` independently. `format` accepts `jpeg` or `png` and defaults to `jpeg`. `size` accepts `scaled` or `full` and defaults to `scaled`. `scaled` uses point dimensions; `full` preserves native pixel resolution. PNG images have no alpha channel.

For a full-resolution PNG:

```bash CLI
lim ios screenshot app-store.png --format png --size full
```

```ts TypeScript
import { promises as fs } from 'node:fs';

const shot = await client.screenshot({ format: 'png', size: 'full' });
await fs.writeFile('app-store.png', Buffer.from(shot.base64, 'base64'));
```

Duo callers can use `screenshotDisplay('inner', { format: 'png', size: 'full' })` or CLI `--display inner --format png --size full`. Tap coordinates remain in points; use `tapWithScreenSize` when working from native pixel coordinates.

### Wait for the screen to settle

A tree read during a transition, or while data loads, describes a screen that is about to change. Give the read a wait in milliseconds, up to 30000, and the simulator keeps reading until two reads in a row match and the screen draws fewer than 15 frames a second. A blinking text cursor draws about 10, so a screen with a focused field still settles.

```bash CLI
lim ios element-tree --wait-for-idle-timeout-ms 3000 --json
```

```ts TypeScript
const read = await client.readElementTree(undefined, { waitForIdleTimeoutMs: 3000 });
// read.tree: the element tree
// read.idle: false when the screen was still changing at the end of the wait
```

```go Go
read, err := client.ReadElementTree(ctx, nil, iosws.ElementTreeOptions{
    WaitForIdleTimeout: 3 * time.Second,
})
// read.Tree: the element tree
// *read.Idle: false when the screen was still changing at the end of the wait
```

When the wait runs out, the read still returns the latest tree: the CLI prints a warning on stderr, and the SDKs set `idle` to `false`. A spinner or another endless animation never settles, so a read on that screen takes the whole wait. The wait needs `lim` 0.64.0, TypeScript SDK 0.78.0, or Go SDK v0.14.0 or later.

### Read navigation bars, tab bars, and the keyboard

The default tree is the one accessibility tools such as VoiceOver read. It has no containers for navigation bars or tab bars, and it leaves out elements the software keyboard covers. The `xcuitest` source reads XCTest's snapshot instead, the tree XCUITest queries. In it, navigation bars, tab bars, and the keyboard are `NavigationBar`, `TabBar`, and `Keyboard` elements with their children inside, and covered elements stay in the tree:

```bash CLI
lim ios element-tree --source xcuitest --json | jq '.. | objects | select(.type == "TabBar")'
```

```ts TypeScript
const read = await client.readElementTree(undefined, { source: 'xcuitest' });
// read.modal: the alert covering the app, or null
```

```go Go
read, err := client.ReadElementTree(ctx, nil, iosws.ElementTreeOptions{
    Source: iosws.ElementTreeSourceXCUITest,
})
// read.Modal: the alert covering the app, or nil
```

The snapshot differs from the default tree in a few ways:

- An `xcuitest` read takes about a second and always reads the whole tree, so it can't be combined with a point or with `--visible-only` (SDK: `visibleOnly`).
- Views that XCTest has no type for keep their UIKit class name in `type`, such as `UIKit._UITabBarItemPlatterView`. Match those by `AXLabel` or `AXUniqueId`.
- `tap-element` searches the default tree. To tap an element that only the `xcuitest` tree shows, tap the center of its `frame` with `lim ios tap`. Both use the same points.
- Alerts have no element type of their own. The SDKs report the alert covering the app as `modal`: `kind` is `app` for the app's own alert or confirmation dialog and `system` for a system prompt, such as a permission request, and `label` is the alert's title. Sheets are not reported.
- Reading the `xcuitest` tree turns on the simulator's automation mode, and it stays on, as after any XCUITest run.

The `xcuitest` source needs the same versions as the wait above.

## Tap an element

Select elements by accessibility ID first, then by label, and use coordinates only as a last resort. Accessibility selectors survive layout changes; coordinates do not.

```bash CLI
lim ios tap-element --ax-unique-id startButton
lim ios tap-element --ax-label "Save"
lim ios tap-element --ax-label-contains continue
lim ios tap-element --type Button --ax-label "Done"
lim ios tap 201 450
```

```ts TypeScript
// By accessibility identifier (most stable)
await client.tapElement({ AXUniqueId: 'startButton' });

// By label
await client.tapElement({ AXLabel: 'Save' });

// By label contains (case-insensitive)
await client.tapElement({ AXLabelContains: 'continue' });

// By type + label
await client.tapElement({ type: 'Button', AXLabel: 'Done' });

// By coordinates (last resort)
await client.tap(201, 450);
```

```go Go
// ctx and client come from the connect step above.
// Selector field names differ slightly from TypeScript:
//   AccessibilityID, Label, LabelContains, ElementType, Title, TitleContains, Value
_, err := client.TapElement(ctx, iosws.AccessibilitySelector{
    AccessibilityID: "startButton",
})
_, err = client.TapElement(ctx, iosws.AccessibilitySelector{
    Label: "Save",
})
_, err = client.TapElement(ctx, iosws.AccessibilitySelector{
    ElementType: "Button",
    Label:       "Done",
})
err = client.Tap(ctx, 201, 450)
```

`tap-element` accepts `--ax-unique-id`, `--ax-label`, `--ax-label-contains`, `--type`, `--title`, `--title-contains`, and `--ax-value`. Every field you pass must match (AND, not OR). The `contains` variants are case-insensitive.

The TypeScript selector fields are `AXUniqueId`, `AXLabel`, `AXLabelContains`, `type`, `title`, `titleContains`, and `AXValue`. Go names the same fields `AccessibilityID`, `Label`, `LabelContains`, `ElementType`, `Title`, `TitleContains`, and `Value`.

`tapElement` taps with a real synthesized touch, so the app reacts as it would to a finger. Elements the accessibility tree can see are scrolled into view before the tap. A selector that matches nothing fails in about a second, and iOS creates list rows lazily, so a row below the fold is often missing from the tree. For those rows, pass `--scroll-search` (SDK: `{ scrollSearch: true }`): it pages the screen and retries until the row appears, up to three screens down and six screens up, within the call's time budget (`timeoutMs` in the SDK, 90 seconds by default). `--activate ax` (SDK: `{ activate: 'ax' }`) performs an accessibility press instead: no scrolling and no touch events, but it works on elements without a usable frame.

## Adjust values

Steppers, sliders, and text fields can be set directly instead of tapped. `set-text` writes a value through accessibility: the value lands verbatim, but the app's text delegates and keyboard behavior are skipped.

```bash CLI
lim ios set-text "42" --ax-label Count
lim ios set-text "P@ssw0rd!" --focused
```

```ts TypeScript
await client.incrementElement({ AXLabel: 'Volume' });
await client.decrementElement({ AXLabel: 'Volume' });
await client.setElementValue('42', { AXLabel: 'Count' });   // sets the exact value, no keyboard involved
await client.setElementValue('P@ssw0rd!');                  // no selector: targets the focused field
```

TypeScript only: `incrementElement` and `decrementElement` increment and decrement a stepper or slider.

Use `set-text` to seed field values. Use `type`, below, when the app must react as if a user typed.

`set-text` can't write to a field the software keyboard covers. It fails with the `covered_by_keyboard` code rather than write to a key. Type into the field, or scroll it above the keyboard first.

## Type and press keys

`type` sends real hardware key events into the focused field: text delegates fire, and the field's own keyboard behavior applies (a default text field capitalizes the first letter, for example). It fails when no field has focus, so tap the field first. If you focused a field another way, such as a coordinate tap, and the focus check misreads it, pass `--no-require-focus` to type anyway.

`type` also reaches a focused field that the software keyboard covers. iOS leaves covered elements out of the element tree, so `type` takes the keyboard itself as proof that a field has focus.

```bash CLI
lim ios type "hello world" --enter          # press Enter after typing
lim ios type "hi" --no-require-focus
lim ios press-key @                         # shifted symbols work directly
lim ios press-key enter --modifier shift
lim ios toggle-keyboard
```

```ts TypeScript
await client.typeText('hello world');                   // types into focused field
await client.typeText('email@example.com', true);       // pressEnter = true
await client.typeText('hi', false, { requireFocus: false }); // skip the focus check
await client.pressKey('enter');
await client.pressKey('a', ['shift']);                   // modifiers: shift, command, control, alt
await client.toggleKeyboard();
```

```go Go
err := client.TypeText(ctx, "hello world", false)
err = client.TypeText(ctx, "email@example.com", true) // pressEnter
err = client.PressKey(ctx, "enter")
err = client.PressKey(ctx, "a", "shift")
// toggleKeyboard is not in Go SDK v0.9.0.
```

`press-key` accepts shifted symbols (`@`, `#`, `?`) and adds the shift itself. `--modifier` is repeatable and accepts `shift`, `command`, `control`, and `alt`. `toggle-keyboard` is the equivalent of pressing ⌘K in the simulator.

### Check where typed text goes

`focused-element` returns the element that has focus and the software keyboard's frame. When it reports a keyboard but no element, the focused field is under the keyboard: `type` reaches it, and `set-text` doesn't.

```bash CLI
lim ios focused-element
# The focused input is under the software keyboard at 0,546 402x328. ios type still reaches it; ios set-text cannot.
```

```ts TypeScript
const focus = await client.focusedElement();
// focus.element: the focused element, or null
// focus.keyboard: { frame } while the software keyboard shows, or null
```

```go Go
focus, err := client.FocusedElement(ctx)
// focus.Element: the focused element, or nil
// focus.Keyboard: the software keyboard's frame, or nil
```

In the SDKs, a default-source `readElementTree` reports the same `keyboard` field alongside the tree. `focused-element` needs `lim` 0.64.0, TypeScript SDK 0.78.0, or Go SDK v0.14.0 or later.

## Scroll and swipe

`scroll` is a finger-swipe gesture. `--amount` is the distance in pixels (default 300), `--coordinate` is the start point (default: the screen center; set it when the scrollable view is elsewhere, such as in a modal), and `--momentum` from 0.0 to 1.0 controls the fling. Directions follow the app's interface orientation. For a landscape interface, pass the landscape coordinates from the element tree, even when the simulated device stays portrait.

```bash CLI
lim ios scroll down --amount 300
lim ios scroll up --amount 300 --momentum 0.4 --coordinate 200,400
```

```ts TypeScript
await client.scroll('down', 300);
await client.scroll('up',   300, { coordinate: [200, 400], momentum: 0.4 });
```

For gestures with explicit start and end points, such as pull-to-refresh, carousel paging, or sliders, use `swipe`. Longer durations drag more precisely; shorter ones fling. The default is 300 ms.

```bash
lim ios swipe --from 200,300 --to 200,600                 # pull-to-refresh: drag down from inside the content
lim ios swipe --from 350,400 --to 50,400 --duration 800   # slow horizontal drag
```

CLI only: the SDKs have no `swipe` call. In TypeScript, compose a swipe from touch actions in [a batch](#run-a-batch-of-actions).

## Rotate the device

Turn the device to portrait, upside down, or either landscape, or use a `setOrientation` action in [a batch](#run-a-batch-of-actions):

```bash CLI
lim ios set-orientation landscape-right
lim ios set-orientation portrait-upside-down   # or portrait, landscape-left
```

```ts TypeScript
await client.setOrientation('LandscapeRight');
await client.setOrientation('PortraitUpsideDown'); // or 'Portrait', 'LandscapeLeft'
```

```go Go
err = client.SetOrientation(ctx, iosws.OrientationPortrait)
err = client.SetOrientation(ctx, iosws.OrientationLandscape)
```

The orientations are the interface orientations `lim ios info` reports, so a value read there can be set again. `Landscape` is the older name of `LandscapeRight`. Go SDK v0.9.0 has only portrait and landscape. For an iPhone Duo, use `lim ios fold --orientation`; see [Fold an iPhone Duo](#fold-an-iphone-duo).

## Open URLs and deep links

`open-url` opens web URLs in Safari and registered URL schemes in their apps:

```bash CLI
lim ios open-url "https://apple.com"
lim ios open-url "myapp://orders/42"
```

```ts TypeScript
await client.openUrl('https://apple.com');               // opens in Safari
await client.openUrl('myapp://orders/42');               // deep link into your app
```

```go Go
err = client.OpenURL(ctx, "https://apple.com")
err = client.OpenURL(ctx, "myapp://orders/42")
```

## Run a batch of actions

When a sequence should run without a round trip between steps, send it as one batch. The server runs the whole batch next to the simulator. It stops at the first failing action, and the call fails with that action's error. When every action succeeds, it returns one result per action. Agents use this for anything longer than a single tap.

```bash CLI
lim ios perform \
  --action 'type=tapElement,selector={"AXLabel":"Continue"}' \
  --action type=wait,durationMs=500 \
  --action "type=typeText,text=hello,pressEnter=true"
```

```ts TypeScript
const result = await client.performActions(
  [
    { type: 'tapElement', selector: { AXLabel: 'Continue' } },
    { type: 'wait', durationMs: 500 },
    { type: 'typeText', text: 'hello', pressEnter: true },
    { type: 'scroll', direction: 'down', pixels: 300 },
    { type: 'pressKey', key: 'enter' },
  ],
  { timeoutMs: 10_000 },
);
// result.results has one entry per action; a failing action rejects the call instead
```

Longer CLI sequences read better from a YAML or JSON file:

```bash
lim ios perform --file ./actions.yaml
```

```yaml title="actions.yaml"
- type: tapElement
  selector: { AXLabel: "Continue" }
- type: wait
  durationMs: 500
- type: typeText
  text: "hello"
  pressEnter: true
```

The CLI sizes the batch timeout from its waits and action count; override it with `--timeout <ms>`. In TypeScript, pass `timeoutMs` as shown above.

Action `type` values fall into two groups:

- **High-level**, one to one with the single-action commands: `tap`, `tapElement`, `incrementElement`, `decrementElement`, `setElementValue`, `typeText`, `pressKey`, `scroll`, `toggleKeyboard`, `openUrl`, `setOrientation`, `wait`.
- **Raw HID**, for custom gestures: `touchDown`, `touchMove`, `touchUp`, `keyDown`, `keyUp`, `buttonDown`, `buttonUp`, `usageDown`, `usageUp`.

Hardware `button` values for `buttonDown` and `buttonUp` are `home`, `lock`, `side`, `applePay`, and `softwareKeyboard`. A native iPhone Duo also supports `volumeUp` and `volumeDown`.

`usageDown` and `usageUp` press any USB HID usage by `usagePage` and `usage`, such as a media or brightness key. Page `7` usages are keyboard keys. For example, page `12` (Consumer) usage `111` is Brightness Increment:

```bash
lim ios perform --action type=usageDown,usagePage=12,usage=111 --action type=usageUp,usagePage=12,usage=111
```

### Build custom gestures

Pair `touchDown`, `touchMove`, and `touchUp` with `wait` actions to build long presses, flings with custom inertia, or anything `scroll` does not cover. This drag moves one finger up the screen:

```ts
const cx = client.deviceInfo.screenWidth / 2;
const startY = 600;
const endY = 200;

await client.performActions([
  { type: 'touchDown', x: cx, y: startY },
  { type: 'wait', durationMs: 30 },
  { type: 'touchMove', x: cx, y: startY - 100 },
  { type: 'touchMove', x: cx, y: startY - 200 },
  { type: 'touchMove', x: cx, y: endY },
  { type: 'touchUp',   x: cx, y: endY },
]);
```

For a two-finger gesture, add `x2` and `y2` to every `touchDown`, `touchMove`, and `touchUp`. Each event moves both fingers together. Keep the same finger order throughout the gesture and lift both fingers with `touchUp`. Supplying only one of `x2` or `y2` rejects the batch before it runs. One or two fingers are supported; omit both fields for a single finger.

Both fingers share one coordinate space. Without `screenWidth` and `screenHeight`, coordinates use the device's display size in its current orientation. To use coordinates from a resized image, pass that image's width and height on every touch action; the server scales and rotates both fingers.

A two-finger tap from the CLI:

```bash
lim ios perform \
  --action type=touchDown,x=100,y=300,x2=200,y2=300 \
  --action type=wait,durationMs=100 \
  --action type=touchUp,x=100,y=300,x2=200,y2=300
```

This TypeScript pinch-out spreads two fingers apart over 320 milliseconds:

```ts
import type { Ios } from '@limrun/api';

type TwoFingerAction = Ios.PerformAction & { x2?: number; y2?: number };
const cx = client.deviceInfo.screenWidth / 2;
const cy = client.deviceInfo.screenHeight / 2;
const actions: TwoFingerAction[] = [
  { type: 'touchDown', x: cx - 20, y: cy, x2: cx + 20, y2: cy },
];
for (let step = 1; step <= 8; step++) {
  const spread = 20 + step * 10;
  actions.push(
    { type: 'wait', durationMs: 40 },
    { type: 'touchMove', x: cx - spread, y: cy, x2: cx + spread, y2: cy },
  );
}
actions.push({ type: 'touchUp', x: cx - 100, y: cy, x2: cx + 100, y2: cy });
await client.performActions(actions);
```

The example assumes portrait orientation. The local `TwoFingerAction` type adds `x2` and `y2` in case your installed SDK's type definitions lack them; the runtime accepts them either way.

`x` and `y` are the first finger; `x2` and `y2` are the second. `lim ios perform --file actions.json` accepts the same actions array as JSON, so you can save a gesture and replay it from the CLI. To zoom out, start with the fingers apart and move them toward each other before lifting both.

## Handle failed commands

When the simulator rejects a command, the error carries a stable `code`, so you can branch on the reason without matching message text. `type`, `set-text`, and `press-key` also report `written`. `none` means nothing reached the app, so a retry can't type the text twice. `unknown` means input had started, and some of it may have landed.

```bash CLI
lim ios type "hello" --json
# Exits with status 1 and prints this to stderr:
# {"error":{"code":"no_focused_element","message":"No focused accessibility element found","written":"none"}}
```

```ts TypeScript
try {
  await client.typeText('hello');
} catch (err) {
  if (!(err instanceof Ios.CommandError) || err.code !== 'no_focused_element') throw err;
  // err.written is 'none': nothing was typed, so focus the field and retry.
  await client.tapElement({ AXUniqueId: 'emailField' });
  await client.typeText('hello');
}
```

```go Go
err := client.TypeText(ctx, "hello", false)
var cmdErr *iosws.CommandError
if errors.As(err, &cmdErr) && cmdErr.Code == "no_focused_element" {
    // cmdErr.Written is iosws.WrittenNone: nothing was typed, so focus the field and retry.
}
```

A failed batch reports the `code` and `written` of the action that failed. The codes are:

| Code | Meaning |
|---|---|
| `no_focused_element` | No field has focus, and the software keyboard is hidden. Tap the field first. |
| `covered_by_keyboard` | `set-text` targeted a field the software keyboard covers. Use `type`, or scroll the field above the keyboard. |
| `element_not_found` | The selector matched no element. |
| `ambiguous_selector` | The selector matched more than one element. Add fields to the selector. |
| `ambiguous_focus` | More than one element reports focus. |
| `no_usable_frame` | The matched element has no frame to aim at. `tap-element --activate ax` works without one. |
| `busy` | A conflicting command, such as another `type`, is still running. |
| `invalid_request` | The request is malformed, such as an unknown key name or an `xcuitest` read with a point. |
| `unavailable` | The simulator can't serve the command right now, such as an `xcuitest` read that timed out. Retry it. |
| `input_failed` | Sending input failed after it started. Check `written` before you retry. |
| `internal` | An unexpected failure. |

New codes may appear, so treat a code you don't recognize as a failure. Codes need `lim` 0.64.0, TypeScript SDK 0.78.0, or Go SDK v0.14.0 or later.

## Manage apps

List, launch, terminate, and install apps by bundle ID. `list-apps` includes system apps.

`lim ios list-apps --json` and TypeScript `listApps()` include `pid` only for apps running at query time. The CLI table shows the same value in its PID column. A PID can belong to a background app and does not indicate that the app is responsive.

```bash CLI
lim ios list-apps
lim ios launch-app com.example.MyApp --mode RelaunchIfRunning
lim ios terminate-app com.example.MyApp
lim ios install ./MyApp.app.zip
lim ios install --asset-name releases/MyApp.app.zip
lim ios install https://... --md5 abc... --launch-mode ForegroundIfRunning
```

```ts TypeScript
const apps = await client.listApps();
// [{ bundleId, name, installType }, ...]

await client.launchApp('com.example.MyApp');
await client.launchApp('com.example.MyApp', 'RelaunchIfRunning');
await client.launchApp('com.example.MyApp', {
  mode: 'RelaunchIfRunning',
  onExit: (logs, info) => {
    console.log(info.reason, info.crash?.shortMsg);
    for (const line of logs) console.log(line);
  },
});

const monitor = await client.monitorApp('com.example.MyApp', {
  onExit: (logs, info) => console.log(info.reason),
  onHang: (hang) => console.log(hang.durationMs),
});
await monitor.stop();

await client.terminateApp('com.example.MyApp'); // fires onExit with reason 'terminated'

// Install from a URL (md5 enables server-side caching)
await client.installApp('https://...build.zip', {
  md5: '...',
  timeoutMs: 120_000,
  launchMode: 'ForegroundIfRunning',
});
```

```go Go
apps, err := client.ListApps(ctx)
// []InstalledApp{ BundleID, Name, InstallType }

err = client.LaunchApp(ctx, "com.example.MyApp")
result, err := client.InstallApp(ctx, "https://...build.zip", &iosws.AppInstallationOptions{
    MD5:        "...",
    LaunchMode: "ForegroundIfRunning",
})
// terminateApp is not in Go SDK v0.9.0; use `lim ios terminate-app` instead.
```

`launch-app` streams the app's logs and exits when the app exits. It prints each main-thread hang with the top of its stack, then the exit reason and, after a crash, the crash details. CLI only: pass `--detach` to return right after the launch, for example in scripts. `install` accepts a local archive, a remote URL, or `--asset-name <name>`. For local archives, the CLI uploads to Asset Storage and installs by name. Before a named install, it adds any missing asset read permission to the instance role while preserving existing grants. See [Install by asset name](/platform/asset-storage#install-by-asset-name) for delegation requirements. `--md5` (SDK: `md5`) enables server-side install caching for remote URLs. If you don't know the bundle ID, check the Xcode project or run `list-apps` after a successful build.

TypeScript only: `onExit` and `onHang`, on `launchApp` or `monitorApp`, report how an app ended and when its main thread hangs; see [React to crashes and exits](#react-to-crashes-and-exits) and [React to hangs](#react-to-hangs).

### Set app environment variables

Pass `--env KEY=VALUE` for each variable the app needs at launch:

```bash
lim ios launch-app com.example.MyApp \
  --env API_URL=https://api.example.com \
  --env FEATURE_FLAG=1
```

In TypeScript, pass an `env` object:

```ts
await client.launchApp('com.example.MyApp', {
  env: { API_URL: 'https://api.example.com', FEATURE_FLAG: '1' },
});
```

Providing variables restarts an already-running app. Combining them with
`ForegroundIfRunning` returns an error. Use `--env KEY=` for an empty value;
if you repeat a key, the last value wins. Values can contain `=`.

[Preview links](/ci/pr-previews#configure-the-preview-app) also accept app
environment variables.

### React to crashes and exits

Use `onExit` on `launchApp`, or on `monitorApp` for an app you didn't launch through the client, when your runner needs to know why an app stopped. On `launchApp` it calls back once, when the launched app exits. On `monitorApp` it calls back at every exit of the app until you stop the monitor. Each call gets the log lines and an `info` object:

- `info.reason` is `crash` when the app died on a fatal signal, `terminated` when it was stopped through `terminateApp` or a relaunch, and `exit` when it ended on its own.
- `info.crash` is set for crashes. `shortMsg` names the exception and signal, for example `EXC_BAD_ACCESS (SIGSEGV) at 0x10`. `longMsg` carries the crash message the app left, such as a Swift `Fatal error: ...` line or an uncaught exception's reason. `stackTrace` lists the crashed thread's frames, with symbol names for the app's own code, followed by the binary images those frames belong to.
- `logs` holds the stdout and stderr lines of that launch. `monitorApp` callbacks get no log lines.

`monitorApp` follows every process of the app, including ones started later, for example by a deep link or a test runner's relaunch:

```ts
const monitor = await client.monitorApp('com.example.MyApp', {
  onExit: (logs, info) => {
    if (info.reason === 'crash') console.log(info.crash?.longMsg, info.crash?.stackTrace);
  },
});
await client.openUrl('myapp://orders/42');
// ... run your tests ...
await monitor.stop();
```

`watchApp`, which reports only the next exit, is deprecated in favor of `monitorApp`.

The frames show function names, not file and line. To get file and line, symbolicate a frame with your build's dSYM: take the load address of the frame's image from the `Binary Images` lines at the end of `stackTrace`.

```bash
atos -arch arm64 -o MyApp.app.dSYM/Contents/Resources/DWARF/MyApp -l <load address> <frame address>
```

Only the app process ending counts as an exit. A JavaScript error that shows the React Native or Expo red error screen keeps the process running, so it reports nothing.

### React to hangs

An app hangs when its main thread stops answering: the screen freezes, and automation calls that read the screen wait until the thread answers again. Use `onHang` on `launchApp` or `monitorApp` when your runner needs to know where the app was stuck. This example prints each hang as it happens:

```ts
const monitor = await client.monitorApp('com.example.MyApp', {
  onHang: (hang) => {
    if (hang.ended) console.log(`hang ${hang.hangId} ended after ${hang.durationMs} ms`);
    else console.log(`hung ${hang.durationMs} ms, ${hang.mainThreadState}`, hang.stackTrace);
  },
});
// ... run your tests ...
await monitor.stop();
```

A hang starts once the main thread hasn't answered for 1 second. The callback gets a sample 1, 3, 6 and 10 seconds in, then once more when the main thread answers or the app exits:

- `hang.ended` is `false` for a sample and `true` for the hang's end. `durationMs` is the hang's age at a sample, or its whole length at the end. A hang's samples and its end share `hangId`.
- `stackTrace` lists the main thread's frames in the same layout as a crash's `stackTrace`, so you symbolicate it the same way.
- `mainThreadState` and `mainThreadCpuMs` tell a busy app from a waiting one. `running` with CPU time close to `durationMs` means the app kept its main thread busy. `waiting` with CPU time near zero means the thread waited, and the top frame shows on what, such as a lock or a reply from another process.
- `mainThreadKernelMs`, `pageIns`, `appCpuMs` and `footprintBytes` add the kernel's share of that CPU time, pages read in from disk, the CPU time of all the app's threads, and the app's memory footprint.
- Samples leave out any of these fields that the app couldn't read. Ends carry no stack and no counters.

`onHang` on `launchApp` covers that launch only and stops when the launched app exits. `monitorApp` keeps reporting across relaunches until you call `stop()`, so it suits runners that relaunch the app between tests. A simulator keeps its 8 newest monitors, so starting a ninth stops the oldest. Hangs while an app launches, before it first becomes active, are not reported.

### Reset app data between runs

Between test cases, wipe the app's data container and relaunch it instead of reinstalling. The TypeScript SDK does this with `softReset`:

```ts
await client.softReset('com.example.MyApp');                       // strategy: 'data' (default)
await client.softReset('com.example.MyApp', { strategy: 'full' }); // also clears caches, keychain, and privacy grants
// returns: { strategy, bundleId, itemsCleared?, durationMs }
```

## Read app logs

App logs cover an app you installed however it was opened, including a tap in the stream or `lim ios open-url`.

Tail recent lines (default 100) or stream live output for one app:

```bash CLI
lim ios app-log com.example.MyApp --tail 200
lim ios app-log com.example.MyApp --follow
```

```ts TypeScript
// One-shot tail
const tail = await client.appLogTail('com.example.MyApp', 200);

// Stream live
const stream = client.streamAppLog('com.example.MyApp');
stream.on('line', (line) => console.log(line));
stream.on('error', console.error);
stream.on('close', () => console.log('stream closed'));
stream.stop();   // unsubscribe when done
```

In TypeScript, the stream emits one `line` event per log line, batched about every 500 ms on the server, plus `error` and `close`.

For low-level debugging beyond one app's stdout and stderr, stream the simulator's syslog until you interrupt it:

```bash
lim ios syslog --id <instance-id>
```

## Check app CPU and memory

The simulator samples the CPU and memory of every running app you installed once a second and keeps the last ten minutes. You can read them at any point without starting a capture first. System apps are not measured. App performance needs `lim` 0.54.0 or later, or `@limrun/api` 0.71.0 or later.

Read the latest figures, or follow new samples as they arrive:

```bash CLI
lim ios perf
lim ios perf --app com.example.MyApp --since 2m
lim ios perf --follow
```

```ts TypeScript
const stop = client.streamPerformance({
  onSample: (sample) => {
    if (sample.bundleId !== 'com.example.MyApp') return;
    const mb = (sample.footprintBytes / 1024 / 1024).toFixed(1);
    console.log(`${sample.cpuPercent ?? '-'}% CPU, ${mb} MB`);
  },
  onError: (err) => console.error(err),
});
// ... drive the app ...
stop();
```

`lim ios perf` prints each app's CPU, memory, peak memory, thread count, disk read and write rates, and busiest threads from the latest sample, then exits. It reads the samples the simulator already keeps, so it doesn't wait for new ones, and it lists an app that stopped in the last ten minutes as stopped. These flags change what it reports:

| Flag | What it does |
|---|---|
| `--app <bundle-id>` | Report only this app. |
| `--since <duration>` | Summarize a recent window, such as `30s` or `2m`, up to `10m`. For each app it prints the number of samples, the average and highest CPU, the latest memory and thread count, and the highest memory sampled in the window. |
| `--follow` | Print one line per app per second until you press `Ctrl+C`. Can't be combined with `--since`. |
| `--json` | Print an array with the newest sample of each app. With `--since`, print one summary per app with its samples in `series`. With `--follow`, print one sample per line. |

To interpret the figures:

- CPU counts one fully busy core as 100%, so an app that keeps several cores busy reads above 100%.
- Memory is the app's physical footprint, the figure Xcode's memory gauge shows. Peak is the highest footprint that process reached.
- The main thread appears among the busiest threads as `main`.
- Test runners, such as WebDriverAgent and other XCTest runners whose bundle IDs end in `.xctrunner`, are measured too. The CLI marks them `(test runner)`.
- The figures come from the Mac that runs the simulator, and the simulator enforces no iOS memory limit. Compare an app with its own earlier figures, not with a device's memory budget.

In TypeScript, `streamPerformance` first replays the samples the simulator kept, then delivers each new one. Call the function it returns to stop the stream. Each `PerformanceSample` holds the figures above in `cpuPercent`, `footprintBytes`, `peakFootprintBytes`, `threadCount`, `diskReadBytesPerSecond`, `diskWriteBytesPerSecond`, and `topThreads`. `topThreads` lists up to five `{ name, cpuPercent }` entries, busiest first. A sample also has these fields:

- `bundleId` names the app, and `testRunner` is `true` for a test runner.
- `ts` is the sample time and `startedAt` the process start, both in epoch milliseconds. `pid` changes when the app relaunches.
- The CPU and disk rates cover the second since the process's previous sample, so the first sample of a process has no `cpuPercent` and no disk rates.

To keep samples beyond ten minutes, save a performance capture; see [Keep captures after the session](#keep-captures-after-the-session). In the console, the inspector beside a running device has a **Performance** tab that charts CPU and memory live. For a terminated instance, **Open** on the **Instances** page shows a saved capture as charts next to the recording.

## Record a video

For anything that moves (animations, gestures, games), record a video instead of taking screenshots, and attach it to the pull request. Recording runs on the server. `--quality` accepts integers from `5` (default) to `10`; higher values increase fidelity and file size.

```bash CLI
lim ios record start --quality 5
# ... drive the UI ...
lim ios record stop -o /tmp/demo.mp4
# or upload straight to your own bucket:
lim ios record stop --presigned-url "<url>"
```

```ts TypeScript
await client.startRecording({ quality: 5 });
// ... drive the UI ...
const downloadUrl = await client.stopRecording({ localPath: '/tmp/demo.mp4' });
// or:
await client.stopRecording({ presignedUrl: '<your-s3-upload-url>' });
```

Recordings include touch ripples and drag trails by default on iPhone and iPad simulators. To omit them, use `lim ios record start --no-touch-indicators` or pass `touchIndicators: false` to `client.startRecording()`.

This option also hides indicators in live views and screenshots for the duration of the recording. When the last active recording stops or fails, the simulator shows touches again.

TypeScript only: `stopRecording` can save to a local file and hand the bytes to a presigned URL in the same call.

### Multiple recordings

Each recording can start and stop independently. Both commands accept an optional recording ID:

```bash
lim ios record start run-1
lim ios record start run-2
lim ios record stop -o run-2.mp4
lim ios record stop run-1 -o run-1.mp4
```

`start` generates an ID when you omit it and prints the ID after recording begins. With `--json`, the response includes `recordingId`. `stop` without an ID selects the most recently started recording that is still active. It skips recordings already stopping or uploading and leaves other recordings running. If none are active, it returns an error. `--id` continues to select the instance.

IDs use 1 to 64 lowercase letters, digits, underscores, or hyphens and start with a letter or digit. An ID cannot be reused during the instance lifetime, so completed recordings keep their original contents.

The TypeScript client exposes the same controls:

```ts
const first = await client.startRecordingSession({ recordingId: 'run-1', quality: 5 });
const second = await client.startRecordingSession({ quality: 5 });
// Perform the actions to record.
await client.stopRecordingSession(undefined, { localPath: 'latest.mp4' });
// Other recordings keep running.
await client.stopRecordingSession(first, { localPath: 'run-1.mp4' });
```

Wait for each start to resolve before performing the actions it should capture. Concurrent recordings must use the same quality, display, and touchIndicators. Up to eight recordings can be active or uploading. Each completed recording has its own authenticated download URL, available until the instance terminates. `stopRecordingSession` also accepts `presignedUrl`, and `startRecordingSession` accepts `persist`.

This requires a runtime and CLI or TypeScript SDK with recording-session support.

### Keep captures after the session

Captures can also be persisted to Limrun storage, so they outlive the CLI process and the instance. Start them when you create the simulator, or persist a recording when you start it:

```bash
lim ios create --record --events --app-logs com.example.myapp --perf --persist-ttl 24h
lim ios record start --persist --persist-ttl 72h
```

`--record` keeps recording until you stop it or the instance terminates. `--events` captures a log of taps, scrolls, and commands, `--app-logs <bundle-id>` launches the app and captures its output, and `--perf` saves the [CPU and memory samples](#check-app-cpu-and-memory) of your apps. Persisted captures are kept for `72h` unless `--persist-ttl` says otherwise. List them afterwards:

```bash
lim ios recordings --id <instance-id>
lim ios events --id <instance-id>
lim ios app-logs --id <instance-id>
lim ios perf-captures --id <instance-id>
```

A capture appears in these lists once it stops: when you stop it, or when the instance terminates. A running capture is not listed yet. Each events, app-logs, and perf-captures entry is a timestamped JSONL file. A performance capture holds one sample per running app per second. With `--json`, each entry includes a short-lived download URL.

TypeScript only: start and stop a performance capture on a running simulator. Only one runs at a time, and a capture you don't stop is saved when the instance terminates:

```ts
await client.startPerformanceCapture({ ttlSeconds: 24 * 60 * 60 }); // default 72h
// ... run your tests ...
await client.stopPerformanceCapture();
const captures = await lim.iosInstances.listPerformanceCaptures(instanceId);
// [{ id, kind: 'performance', startedAt, stoppedAt, expiresAt, sizeBytes, downloadUrl }, ...]
```

## Simulate the camera

Play a video file as the simulator's camera for QR-code scanning, document capture, video-call screens, or any `AVCaptureSession` flow that needs predictable frames. The file uploads to the instance and replaces the live browser camera until you clear it; apps see it through their regular capture pipeline.

```bash CLI
lim ios camera play ./fixtures/qr-scan.mp4
lim ios camera play ./fixtures/intro.mp4 --no-loop
lim ios camera clear
```

```ts TypeScript
await client.setCameraVideo('./fixtures/qr-scan.mp4');                 // loops by default
await client.setCameraVideo('./fixtures/intro.mp4', { loop: false }); // play once
await client.clearCameraVideo();                                       // back to the live camera
```

Without looping, the feed freezes on the last frame after one pass, so the app keeps receiving frames instead of seeing the camera stall. Anything AVFoundation can decode works, such as H.264 or HEVC in `.mp4` or `.mov`. Portrait recordings play upright.

## Simulate the microphone

Play a local audio file (WAV, MP3, M4A, or AAC) as microphone input. Playback loops until you stop it; `--once` plays a single pass:

```bash
lim ios microphone play ./fixtures/sample.wav --id <instance-id>
lim ios microphone play ./fixtures/sample.mp3 --once --id <instance-id>
lim ios microphone stop --id <instance-id>
```

## Set the clipboard

Put text on the simulator clipboard and read it back. Apps paste it like text copied inside the simulator, so the edit menu's Paste shows no permission prompt. For example, to paste a one-time code into a login form:

```bash CLI
lim ios clipboard set "123456"
echo "123456" | lim ios clipboard set
lim ios clipboard get
```

```ts TypeScript
// Run simctl pbcopy and pbpaste; pbcopy reads its text from the stdin option.
await client.simctl(['pbcopy', 'booted'], { stdin: '123456' }).wait();
const { stdout: clipboard } = await client.simctl(['pbpaste', 'booted']).wait();
```

## Read and write user defaults

Read, write, or delete the simulator's user defaults with its `defaults` tool. Pass the arguments after `--`. Apps read defaults at launch, so relaunch the app under test after a change. For example, to switch the device language and region without UI automation:

```bash CLI
lim ios defaults -- write -g AppleLanguages -array fr-FR
lim ios defaults -- write -g AppleLocale -string fr_FR
lim ios defaults -- read -g AppleLanguages
```

```ts TypeScript
await client.simctl(['spawn', 'booted', 'defaults', 'write', '-g', 'AppleLanguages', '-array', 'fr-FR']).wait();
```

`lim ios defaults` accepts only `read`, `write`, and `delete`.

System prompts, such as permission and location alerts, keep the old language until their services restart. Restart them after changing `AppleLanguages`. Restarting SpringBoard closes every running app, and the call returns once SpringBoard is back:

```bash CLI
lim ios restart-services com.apple.SpringBoard com.apple.locationd com.apple.tccd com.apple.akd
```

```ts TypeScript
await client.restartServices(['com.apple.SpringBoard', 'com.apple.locationd', 'com.apple.tccd', 'com.apple.akd']);
```

These four services are the only ones you can restart.

## Post notifications

Post a Darwin notification, or set and read a notification's state, inside the simulator with its `notifyutil` tool:

```bash
lim ios notify post <name>
lim ios notify set <name> <state>
lim ios notify get <name>
```

For example, the simulator drives Face ID through these notifications. Enroll once, then answer each Face ID prompt with a match or a non-match. Touch ID devices use `fingerTouch` in place of `pearl`:

```bash CLI
lim ios notify set com.apple.BiometricKit.enrollmentChanged 1
lim ios notify post com.apple.BiometricKit.enrollmentChanged
lim ios notify post com.apple.BiometricKit_Sim.pearl.match     # the next scan succeeds
lim ios notify post com.apple.BiometricKit_Sim.pearl.nomatch   # the next scan fails
```

```ts TypeScript
// notify post, set, and get are notifyutil -p, -s, and -g.
await client.simctl(['spawn', 'booted', 'notifyutil', '-p', 'com.apple.BiometricKit_Sim.pearl.match']).wait();
```

## Grant privacy permissions

Decide a permission before the app asks, so the system prompt never appears, or read what the app was given:

```bash CLI
lim ios permission set com.example.app camera granted
lim ios permission set com.example.app photos limited          # selected photos only
lim ios permission set com.example.app notifications critical  # critical alerts too
lim ios permission set com.example.app contacts denied
lim ios permission set com.example.app faceid unset            # the app asks again
lim ios permission get com.example.app camera                  # granted, denied, limited, or unset
```

```ts TypeScript
await client.setPermission('com.example.app', 'camera', 'granted');
await client.setPermission('com.example.app', 'photos', 'limited');
const status = await client.getPermission('com.example.app', 'camera'); // 'granted', 'denied', 'limited', or 'unset'
```

The services are `calendar`, `camera`, `contacts`, `faceid`, `health`, `homekit`, `medialibrary`, `microphone`, `motion`, `notifications`, `photos`, `reminders`, `siri`, `speech`, and `usertracking`. `limited` applies only to `photos`, and `critical` only to `notifications`.

Setting `notifications` restarts SpringBoard, which closes every running app, so set it before launching the app under test. The notifications permission cannot be read back. For location, use `lim ios simctl -- privacy booted grant location <bundle-id>`.

## Access a server inside the simulator

Use `lim ios forward` to connect local tools to an HTTP or WebSocket server running inside the simulator:

```bash
lim ios forward 8100 --id <ios-instance-id>
```

This listens on `127.0.0.1:8100` on your machine and forwards connections to port `8100` in the simulator. For example, when WebDriverAgent is running, query it from another terminal:

```bash
curl http://127.0.0.1:8100/status
```

The CLI authenticates the connection to Limrun. Your local client does not need a Limrun token or the SDK. To point Appium at a forwarded WDA, see [Reach WDA through localhost](/testing/appium#reach-wda-through-localhost).

To use different ports, pass `<local-port>:<remote-port>`. Use local port `0` to choose an available port:

```bash
lim ios forward 8080:3000 --id <ios-instance-id>
lim ios forward 0:8100 --id <ios-instance-id> --json
```

The command returns once the local port listens and keeps the forward running in a background process. It prints the process ID; stop the forward with `kill <pid>`. With `--json`, it prints `instanceId`, `localHost`, `localPort`, `remotePort`, `pid`, and `logPath`. To keep the forward in the foreground until you press Ctrl+C, pass `--no-detach`.

Start the server in the simulator separately. It must listen on the simulator's assigned IP or `0.0.0.0`; a server bound only to `127.0.0.1` inside the simulator is not reachable. Forwarding supports TCP protocols where the client sends data first, including HTTP and WebSockets. UDP and protocols where the server sends first are not supported.

To let the simulator reach a service on your machine, use [a destination tunnel](/ios/local-services) instead.

## Send traffic through a proxy

Point the simulator's system proxy at a proxy of your own, so Safari and apps send their HTTP and HTTPS traffic through it:

```bash
lim ios proxy set proxy.example.com:3128
lim ios proxy clear
```

A proxy on your machine or inside your network is reached through a tunnel. See [Send device traffic through a proxy](/networking/proxy) for what goes through the proxy and how to reach one inside your network.

## Trust a CA certificate

Add a CA certificate to the simulator's trusted roots, such as the CA of a [proxy](/networking/proxy) that records HTTPS traffic. The file holds one PEM-encoded CA certificate, and anything else is rejected:

```bash CLI
lim ios ca add ./proxy-ca.pem
```

```ts TypeScript
const { sha256 } = await client.addCaCertificate(fs.readFileSync('./proxy-ca.pem', 'utf8'));
```

`lim ios ca add` needs `lim` 0.45.0 or later, and `addCaCertificate` on the iOS client needs `@limrun/api` 0.64.0 or later. The CLI prints the certificate's SHA-256 fingerprint. Safari and apps trust the CA on their next connection, without a restart, and it stays trusted for the life of the instance. Adding the same certificate again changes nothing. Apps that pin their own certificates still reject it, and so do the simulator's Apple services.

## Transfer files

List a directory to find the exact relative path, then pull, push, or delete files with the same container flags:

```bash CLI
lim ios ls Documents --bundle-id com.example.app --container-type data
lim ios pull-file Documents/recording.mov ./recording.mov \
  --bundle-id com.example.app --container-type data
lim ios push-file ./fixture.json Documents/fixture.json \
  --bundle-id com.example.app --container-type data
lim ios delete-file Documents/fixture.json \
  --bundle-id com.example.app --container-type data
```

```ts TypeScript
import { writeFile } from 'node:fs/promises';

// Pass the same container options to each call.
const container = {
  bundleId: 'com.example.app',
  containerType: 'data',
};

const entries = await client.listFiles('Documents', container);
// [{ name: 'recording.mov', path: 'Documents/recording.mov',
//    isDirectory: false, size: 123456 }]

const recording = await client.pullFile(entries[0].path, container);
await writeFile('./recording.mov', recording);
```

Without `--bundle-id`, file commands target the simulator staging folder. With `--bundle-id`, the default container type is `app`; use `data` for writable app data such as `Documents`, `Library`, and `tmp`, or pass an App Group identifier. Every path that `ls` returns is relative to the selected root and works with the other commands unchanged.

## Save and restore the keychain

[Simulator snapshots](/reference/instances#simulator-snapshots) save all
installed apps, their data, keychain, and supported permissions under a name.
Pass the name to `lim ios create --snapshot-key`. For iOS previews, add
[`snapshot-key`](/ci/pr-previews#keep-app-state-between-previews) to the preview URL.

To save only the keychain, run this command after signing in to your app:

```bash
# The default asset name is "keychain/login.tar.gz"
lim ios keychain save
```

The command stores an unencrypted `.tar.gz` archive as a `Keychain` asset and
prints the matching restore command. To restore it into the current simulator:

```bash
lim ios keychain restore
```

To restore the keychain when creating a simulator:

```bash
lim ios create --reuse-if-exists \
  --label app=my-app --label scenario=logged-in \
  --keychain keychain/login.tar.gz
```

Pass an asset name to save or restore a different keychain:

```bash
lim ios keychain save keychain/test-account.tar.gz
lim ios keychain restore keychain/test-account.tar.gz
```

To wipe every keychain item instead, for example to sign the app out of an account it keeps across reinstalls, reset the keychain. CA certificates added with `lim ios ca add` stay trusted:

```bash CLI
lim ios keychain reset
```

```ts TypeScript
await client.resetKeychain();
```

Current SDK and CLI versions save and restore keychain archives without an
encryption key. Older versions can still save and restore encrypted archives
with the original key; the server continues to support them.

To use an encrypted archive with a current client, restore it with an older
client and its original key, then use the current `lim ios keychain save` command
to save a new `.tar.gz` archive under a different asset name.

## Fold an iPhone Duo

The iPhone Duo model must be available to your organization. Create one, then read or change the hinge:

```bash CLI
lim ios create --model iphone-duo
lim ios fold --json --id <instance-id>
lim ios fold 90 --orientation landscape-left --id <instance-id>
lim ios fold 0 --id <instance-id>
lim ios fold 180 --id <instance-id>
lim ios screenshot ./inner.jpg --display inner --id <instance-id>
lim ios tap 300 200 --display inner --id <instance-id>
```

```ts TypeScript
const fold = await client.getFoldState(); // null on an ordinary simulator
await client.setHingeAngle(110);
await client.setDuoOrientation('landscape-left');
const inner = await client.screenshotDisplay('inner');
await client.tapDisplay('inner', inner.width / 2, inner.height / 2);
```

The hinge accepts fractional angles from 0° (closed) to 180° (flat). Omit the angle to read the fold state. Use `fold 0` to close and `fold 180` to unfold; there is no separate unfold command. `--orientation` accepts `portrait`, `pud` (portrait upside down), `landscape-left`, or `landscape-right`, and changes independently of the hinge, so `lim ios fold --orientation portrait --id <instance-id>` rotates without moving the hinge.

This drives the native simulator hinge, so apps receive Apple's hinge and layout updates. `tap`, `scroll`, `swipe`, and `perform` follow the active display by default. Pass `--display outer` or `--display inner` to override the target for coordinate input. `screenshot` also accepts these display flags.

`setDuoOrientation` accepts `portrait`, `landscape-left`, `landscape-right`, and `pud`. Display screenshots are upright and default to JPEG data with point dimensions. You can also request PNG or full-resolution pixels; see [Read the screen](#read-the-screen). `tapDisplay` always uses points. Display-specific calls do not activate a display, so fold or unfold first. A display that iOS has turned off returns a black image; a display that is not ready reports an error.

Gestures and scrolls follow the active display. Use `display` to override that target. Coordinates use the selected display's upright screenshot points:

```ts
const { width, height } = await client.screenshotDisplay('inner');
await client.performActions([
  { type: 'touchDown', x: width * 0.4, y: height / 2,
    x2: width * 0.6, y2: height / 2 },
  { type: 'wait', durationMs: 600 },
  { type: 'touchMove', x: width * 0.3, y: height / 2,
    x2: width * 0.7, y2: height / 2 },
  { type: 'touchUp', x: width * 0.3, y: height / 2,
    x2: width * 0.7, y2: height / 2 },
], { display: 'inner' });
await client.scroll('down', 300); // active display
await client.scroll('down', 300, { display: 'inner' }); // explicit override
```

For two-finger gestures, supply `x2` and `y2` together and keep both contacts through down, move, and up. Each new action resolves the active panel when `display` is omitted. A held raw touch keeps its original panel until touch-up, including across waits. `tapElement`, including scroll search and batched element taps, follows the active display.

Default screenshots capture the active display. Default recordings follow the active display across folds. The video keeps its initial canvas size and letterboxes panels with a different aspect ratio. Use `screenshotDisplay('inner')` or `startRecording({ display: 'inner' })` to select one panel. CLI capture overrides are `screenshot --display inner` and `record start --display inner`. These overrides also accept `outer`.

`elementTree()` reads the frontmost app, including on the active inner display, and preserves the accessibility frames reported by iOS. On the iOS 27.1 Duo simulator, the application root can stay at 669 × 951 points while its window and descendants use the upright inner display's 951 × 669 point coordinates. Use the `width` and `height` returned by a default, point-sized `screenshot()` or `screenshotDisplay()` for the canvas. In that full-screen window, descendant coordinates already match the capture; do not clip, scale, or rotate them using the root's size.

If your renderer needs a root that fills the canvas, resize a separate presentation copy and preserve the original tree. Apps in iPhone compatibility mode can report app-local frames inside a centered window, so check their window placement before mapping coordinates. Full-resolution screenshots use pixels, while accessibility frames and taps use points; account for the screenshot scale when drawing overlays.

Read `(await client.getFoldState())?.displays.filter(display => display.active)` after a fold transition to identify active panels. The hinge angle alone cannot identify the active panel. Automatic input, selector actions, and screenshots require exactly one active panel; retry after the fold settles if none or both report active. If the activity query fails, `getFoldState()` still returns geometry but omits `active`. Hinge, orientation, and unsolicited fold-state responses also omit it.

In the browser stream, the Duo starts in a 2D frame and offers a lazy-loaded 3D frame. Both modes provide hinge and rotation controls, touch input on the cover and inner display, and single-finger touch and drag, but not multi-touch. Click or hold the frame's Sleep/Wake and volume buttons to control iOS. In 3D, the position starts unlocked; **Lock position** stops camera rotation while the screen and buttons stay active. Rotating the view moves the camera, while **Rotate device** changes the native orientation. **Laptop view** sets the hinge and orientation; it does not enable Apple's separate Table Mode. To embed the Duo frame in your own app, see [iPhone Duo frame](/platform/embed-simulator#iphone-duo-frame).

## Debug an app with LLDB

Use `lim ios lldb` to attach LLDB to an app running in the simulator. LLDB runs next to the simulator, so you can debug from any machine, including Linux, and pass it the same commands you use locally:

```bash
lim ios lldb --bundle-id com.example.app --id <ios-instance-id> -- --batch -o "bt all"
```

Arguments after `--` go to `lldb` unchanged. With `--batch`, LLDB runs the commands and exits. Without it, LLDB reads commands from standard input until the input ends, so you can pipe a script or type commands in a live session:

```bash
printf 'breakpoint set -n viewDidLoad\ncontinue\nbt\n' | lim ios lldb --bundle-id com.example.app
lim ios lldb --bundle-id com.example.app
```

The app must be running and built for debugging. Xcode debug builds carry the `get-task-allow` entitlement that LLDB needs; release builds do not. Launch the app first with `lim ios launch-app`.

If you built the app with `lim xcode build` and it was installed on an attached simulator, the symbols load by themselves. When the session starts, the Xcode instance sends the build's debug symbols to the simulator, so breakpoints by file and line and `frame variable` work with no extra flag:

```bash
lim xcode build
lim ios lldb --bundle-id com.example.app -- --batch \
  -o "breakpoint set -f ContentView.swift -l 42" -o "continue" -o "frame variable"
```

This covers the latest successful build of the workspace's Xcode instance. If a later build failed, build again before you debug, because the failed build has already replaced the files the symbols come from. Bazel builds are not covered.

For an app built anywhere else, pass its `.dSYM` with `--dsym` when the debug symbols are in a separate bundle. The CLI uploads its DWARF files and loads them before your commands run:

```bash
lim ios lldb --bundle-id com.example.app --dsym ./MyApp.app.dSYM -- --batch \
  -o "breakpoint set -f ContentView.swift -l 42" -o "continue" -o "frame variable"
```

From the TypeScript SDK, `client.lldb()` returns the same kind of handle as `client.simctl()`, with `write()` and `end()` for a session that keeps its input open:

```ts
const session = client.lldb([], { bundleId: 'com.example.app', keepStdinOpen: true });
session.on('stdout', (chunk) => process.stdout.write(chunk));
session.write('bt\n');
session.end(); // LLDB detaches and exits after it has read everything
const { code } = await session.wait();
```

When LLDB detaches or the command ends, the app keeps running. A simulator runs one LLDB session at a time. Backtraces, breakpoints, stepping, `frame variable`, Objective-C expressions, and Python scripting work. Swift expression evaluation, including `po` on Swift values, is not available yet.

## Use macOS dev tools

When the commands above don't cover what you need, the instance exposes a small set of macOS developer tools:

```bash CLI
lim ios simctl -- listapps booted
lim ios xcrun  -- --sdk iphonesimulator --show-sdk-version
lim ios xcodebuild -- -version
lim ios lsof
```

```ts TypeScript
// Streaming simctl
const exec = client.simctl(['listapps', 'booted']);
exec.on('line-stdout', (line) => console.log(line));
exec.on('line-stderr', (line) => console.error(line));
const { code } = await exec.wait();

// One-shot xcrun (limited to --sdk / --show-* flags)
const { stdout } = await client.xcrun(['--sdk', 'iphonesimulator', '--show-sdk-version']);

// xcodebuild version only
await client.xcodebuild(['-version']);

// Upload a local file to the simulator staging folder (returns the path on the host)
const remotePath = await client.pushFile('/local/path/to/config.json', 'config.json');

// Inspect open UNIX sockets
const sockets = await client.lsof();
```

```go Go
// simctl mirrors os/exec.Cmd; pipe to your own writers or buffer the output.
cmd := client.Simctl(ctx, "listapps", "booted")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil { panic(err) }

// Inspect open UNIX sockets
sockets, err := client.Lsof(ctx)

// xcrun, xcodebuild, and file transfer are not in Go SDK v0.9.0.
```

`simctl` streams stdout and stderr. `xcrun` is limited to the `--sdk` and `--show-*` flags, and `xcodebuild` to `-version`.

## Reuse and clean up

Each simulator is single-tenant: only one client should drive it at a time. Scope instances per user, pull request, or session with labels, and let `reuseIfExists` return the same warm instance on the next call. For platform integrators, this matters when a UI action triggers `create`: without reuse, repeated clicks can create hundreds of instances, each billed; with it, they settle on one.

This create call returns the same instance for the same session across multiple agent runs:

```bash CLI
lim ios create --reuse-if-exists --label session=<session-id> --label user=<user-id>
```

```ts TypeScript
const instance = await lim.iosInstances.create({
  wait: true,
  reuseIfExists: true,
  metadata: { labels: { session: sessionId, user: userId } },
});
```

```python Python
instance = client.ios_instances.create(
    wait=True,
    reuse_if_exists=True,
    metadata={"labels": {"session": session_id, "user": user_id}},
)
```

```go Go
instance, err := lim.IosInstances.New(ctx, limrun.IosInstanceNewParams{
    Wait:          param.NewOpt(true),
    ReuseIfExists: param.NewOpt(true),
    Metadata: limrun.IosInstanceNewParamsMetadata{
        Labels: map[string]string{"session": sessionID, "user": userID},
    },
})
if err != nil {
    panic(err)
}
```

Delete an instance when you are done, or list instances by label and delete every match:

```bash CLI
lim ios list --label-selector "agent=ci,issue=LIM-34"
lim ios delete <instance-id>
```

```ts TypeScript
await lim.iosInstances.delete(instance.metadata.id);

const stale = await lim.iosInstances.list({ labelSelector: `user=${userId}`, state: 'ready' });
for await (const inst of stale) {
  await lim.iosInstances.delete(inst.metadata.id);
}
```

```python Python
client.ios_instances.delete(instance.metadata.id)

params = {"label_selector": f"user={user_id}", "state": "ready"}
while page := client.ios_instances.list(**params).items:
    for inst in page:
        client.ios_instances.delete(inst.metadata.id)
    # Page by hand: the iterator stops after the first page.
    params["starting_after"] = page[-1].metadata.id
```

```go Go
if err := lim.IosInstances.Delete(ctx, instance.Metadata.ID); err != nil {
    panic(err)
}

// Page by hand: ListAutoPaging panics on instance lists.
params := limrun.IosInstanceListParams{
    LabelSelector: param.NewOpt("user=" + userID),
    State:         param.NewOpt("ready"),
}
for {
    page, err := lim.IosInstances.List(ctx, params)
    if err != nil {
        panic(err)
    }
    if len(page.Items) == 0 {
        break
    }
    for _, inst := range page.Items {
        if err := lim.IosInstances.Delete(ctx, inst.Metadata.ID); err != nil {
            panic(err)
        }
    }
    params.StartingAfter = param.NewOpt(page.Items[len(page.Items)-1].Metadata.ID)
}
```

CLI only: without an ID, `lim ios delete` removes the last iOS instance the CLI created in this workspace, so list by label first if you created several. `lim ios list` shows ready instances by default; pass `--all` or `--state` for other states.

The console's **Instances** tab shows the same data. Filter by state or label selector, sort by duration or creation time, and reopen any ready instance with one click:

<img src="/images/console/10-instances.png" alt="Console Instances page showing one ready iOS instance with its ID, status, duration, and creation time" />

After a delete, or after the inactivity timeout fires, the row leaves the **Ready** filter. The **All** filter still shows it as `terminated` until it ages out:

<img src="/images/console/14-instances-empty.png" alt="Console Instances page after deleting the ready instance, with no rows under the Ready filter" />

## Troubleshooting

| Symptom or message | Cause | Fix |
|---|---|---|
| `tap-element` fails after about a second with a selector that matched nothing | The element is not in the accessibility tree yet. iOS creates list rows lazily, so rows below the fold are often missing. | Pass `--scroll-search`, or put `scroll` actions before the `tapElement` in a batch. Read `lim ios element-tree` to confirm the selector values. |
| `type` fails with `no_focused_element` | `type` requires a focused text field. | Tap the field first. If you focused it with a coordinate tap and the focus check misreads it, pass `--no-require-focus`. |
| `set-text` fails with `covered_by_keyboard` | The software keyboard covers the field. | Use `type`, which reaches covered fields, or scroll the field above the keyboard. |
| The element tree shows the screen mid-transition | The read ran before an animation or a load finished. | Pass `--wait-for-idle-timeout-ms 3000` to wait for the screen to settle. |
| Typed text is capitalized or autocorrected | `type` sends real key events, so the field's keyboard behavior applies. | Use `set-text` to write the exact value through accessibility. |
| A two-finger batch is rejected before it runs | A touch action has only one of `x2` or `y2`. | Supply both on every `touchDown`, `touchMove`, and `touchUp`, or neither. |
| An iPhone Duo display call reports an error | The display is not active in the current fold state. | Fold or unfold first with `lim ios fold 0` or `lim ios fold 180`. |
| `lim ios delete` removed the wrong instance | Without an ID it deletes the last iOS instance the CLI created in this workspace. | Run `lim ios list` and pass the instance ID. |
| `lim ios perf` prints `No app reported performance` | The simulator measures only running apps you installed. A simulator created before app performance was available reports nothing. | Launch your app, or create a new simulator. |

## Next steps

**[Build with remote Xcode](/ios/build-with-xcode)**

Produce the build that installs onto the simulator.

**[Connect to local services](/ios/local-services)**

Let the app on the simulator reach a server on your machine or VPN.

**[Run XCTest suites](/testing/xctest)**

Run unit and UI test targets on the simulator with `lim xcode test`.

**[Test in-app purchases](/ios/in-app-purchases)**

Serve StoreKit products from a local config and complete purchases without an Apple ID.

**[Embed a device](/platform/embed-simulator)**

Render the simulator in your web app with `<RemoteControl />`.
