# Session Replay iOS Plugin

This article covers how to install Session Replay using the iOS plugin. If your app already uses the Amplitude [iOS Swift SDK](https://amplitude.com/docs/sdks/analytics/ios/ios-swift-sdk) or legacy Amplitude [iOS SDK](https://amplitude.com/docs/sdks/analytics/ios/ios-sdk), use this option.

If you use Segment through their Analytics-Swift SDK and [Amplitude (Actions) destination](https://segment.com/docs/connections/destinations/catalog/actions-amplitude/), choose the [Segment Plugin](https://amplitude.com/docs/sdks/session-replay/session-replay-ios-segment-integration).

If you use a provider other than Amplitude for in-product analytics, choose the [standalone implementation](https://amplitude.com/docs/sdks/session-replay/session-replay-ios-standalone-sdk).

{% callout type="info" heading="Unified SDK" %}
Install the [Unified SDK for Swift](https://amplitude.com/docs/sdks/analytics/ios/unified-sdk) to access Session Replay along with other Amplitude products (Analytics, Experiment). The Unified SDK provides a single entry point for all Amplitude features and simplifies integration by handling initialization and configuration of all components.
{% /callout %}

{% callout type="note" heading="Session Replay and performance" %}

Amplitude built Session Replay to minimize impact on the performance of the iOS apps in which it's installed by:

- Asynchronously processing replay data, to avoid blocking the main user interface thread. The main thread must be used to interact with the view hierarchy, but all processing is performed on a background queue.
- Using batching and lightweight compression to reduce the number of network connections and bandwidth.
- Optimizing view hierarchy processing. Contact Amplitude if you experience issues with hierarchy processing.

{% /callout %}

Session Replay captures changes to an app's view tree, including the main view and all its child views recursively. Session Replay then replays these changes to build a video-like replay. At the start of a session, Session Replay captures a full snapshot of the app's view tree. As the user interacts with the app, Session Replay captures each view change as a diff. When you watch the replay of a session, Session Replay applies each diff back to the original view tree in sequential order to construct the replay. Session replays have no maximum length.

{% callout type="tip" heading="Report issues" %}
To report issues with Session Replay for iOS, go to the [AmplitudeSessionReplay-ios GitHub repository](https://github.com/amplitude/AmplitudeSessionReplay-ios).
{% /callout %}

## Before you begin

The method you use depends on the version of the Amplitude iOS SDK you use.

{% tabs tabs="iOS Swift SDK, iOS SDK (maintenance)" %}
{% tab name="iOS Swift SDK" %}
The Session Replay iOS Plugin requires that:

1. Your application runs on iOS or iPadOS.
2. You use `1.9.0` or higher of the [iOS Swift SDK](https://amplitude.com/docs/sdks/analytics/ios/ios-swift-sdk).

{% /tab %}
{% tab name="iOS SDK (maintenance)" %}
The Session Replay Middleware requires that:

1. Your application runs on iOS or iPadOS.
2. You use `8.22.0` or higher of the [(maintenance) Amplitude iOS SDK](https://amplitude.com/docs/sdks/analytics/ios/ios-sdk).
3. You can provide a device ID to the SDK.

{% /tab %}
{% /tabs %}

### Supported iOS versions

Session replay supports a minimum target version of iOS 13. Over 91% of Apple devices are running iOS 16 or later, per App Store statistics.

## Quickstart

Add the [latest version](https://github.com/amplitude/AmplitudeSessionReplay-iOS) of the plugin to your project dependencies.

{% tabs tabs="Swift SDK, Legacy SDK" %}
{% tab name="Swift SDK" %}
**Swift Package Manager**

Add Session Replay as a dependency in your Package.swift file, or the Package list in Xcode.

```swift
dependencies: [
    .package(url: "https://github.com/amplitude/AmplitudeSessionReplay-iOS", from: "0.12.2")
]
```

For integrating with `Amplitude-Swift`, use the `AmplitudeSwiftSessionReplayPlugin` target.

```swift
.product(name: "AmplitudeSwiftSessionReplayPlugin", package: "AmplitudeSessionReplay")
```

**CocoaPods**

Add the core library and the plugin to your Podfile.

```
pod 'AmplitudeSessionReplay', :git => 'https://github.com/amplitude/AmplitudeSessionReplay-iOS.git', :tag => 'v0.12.2'
pod 'AmplitudeSwiftSessionReplayPlugin', :git => 'https://github.com/amplitude/AmplitudeSessionReplay-iOS.git', :tag => 'v0.12.2'
```

**Configure your application code**

```swift
import AmplitudeSwift
import AmplitudeSwiftSessionReplayPlugin

// Initialize Amplitude Analytics SDK instance
let amplitude = Amplitude(configuration: Configuration(apiKey: API_KEY))

// Create and Install Session Replay Plugin
// Recording will be handled automatically
amplitude.add(plugin: AmplitudeSwiftSessionReplayPlugin(sampleRate: 1.0))
```

{% /tab %}
{% tab name="Legacy SDK" %}
**Swift Package Manager**

Add Session Replay as a dependency in your Package.swift file, or the Package list in Xcode.

```swift
dependencies: [
    .package(url: "https://github.com/amplitude/AmplitudeSessionReplay-iOS", from: "0.12.2")
]
```

For integrating with `Amplitude-iOS`, use the `AmplitudeiOSSessionReplayMiddleware` target.

```swift
.product(name: "AmplitudeiOSSessionReplayMiddleware", package: "AmplitudeSessionReplay")
```

**CocoaPods**

Add the core library and the middleware to your Podfile.

```
pod 'AmplitudeSessionReplay', :git => 'https://github.com/amplitude/AmplitudeSessionReplay-iOS.git', :tag => 'v0.12.2'
pod 'AmplitudeiOSSessionReplayMiddleware', :git => 'https://github.com/amplitude/AmplitudeSessionReplay-iOS.git', :tag => 'v0.12.2'
```

**Configure your application code**

```swift
import Amplitude
import AmplitudeiOSSessionReplayMiddleware

// Initialize Amplitude Analytics SDK instance

let amplitude = Amplitude.instance()

// Although not required, we recommend enabling session start and end events when enabling Session Replay
amplitude.defaultTracking.sessions = true

// Create and Install Session Replay Middleware
// Recording will be handled automatically
amplitude.addEventMiddleware(AmplitudeiOSSessionReplayMiddleware(sampleRate: 0.1))

amplitude.initializeApiKey(API_KEY)
```

{% /tab %}
{% /tabs %}

## Configuration

Pass the following option when you initialize the Session Replay plugin:

| Name                                 | Type             | Required | Default          | Description                                                                                                                                                                                                                                                                                      |
| ------------------------------------ | ---------------- | -------- | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `sampleRate`                         | `Float`          | No       | `0`              | Controls how many sessions Amplitude selects for replay collection. The value is a decimal between 0 and 1 (for example, `0.4`), representing the fraction of sessions Amplitude randomly selects for replay collection. Over a large number of sessions, `0.4` selects `40%` of those sessions. |
| `enableRemoteConfig`                 | `Bool`           | No       | `true`           | Enables or disables [remote configuration ](#remote-configuration) for this instance of Session Replay.                                                                                                                                                                                          |
| `autoStart`                          | `Bool`           | No       | `true`           | Controls whether Session Replay begins capturing automatically when it initializes.                                                                                                                                                                                                              |
| `maskLevel`                          | `MaskLevel`      | No       | `.medium`        | Sets how much on-screen content Session Replay masks. Use `.light`, `.medium`, or `.conservative`. For more detail, refer to [Mask level](#mask-level).                                                                                                                                          |
| `captureWebViews`                    | `Bool`           | No       | `false`          | Enables capture of web view content. By default, Session Replay blocks web views.                                                                                                                                                                                                                |
| `webviewMappings`                    | `[String: String]` | No       | `[:]`            | Maps substrings in captured web view content to replacement values. When you enable `captureWebViews`, Session Replay applies each entry as a case-insensitive find-and-replace on the web view recording data before upload. This is an advanced option; most apps leave it empty.              |
| `recordLogOptions.logCountThreshold` | `Int`            | No       | `1000`           | Sets the maximum number of logs per session.                                                                                                                                                                                                                                                     |
| `recordLogOptions.maxMessageLength`  | `Int`            | No       | `2000`           | Sets the maximum length of a log message.                                                                                                                                                                                                                                                        |
| `quality`                            | `QualityProfile` | No       | `.high`          | Controls capture and encoding quality (for example, frame rate and image resolution). Use `.low`, `.medium`, or `.high` to balance replay fidelity with performance and storage. Use `QualityProfile.automatic` to let the SDK choose a profile based on the device.                             |
| `uploadConfig`                       | `UploadConfig`   | No       | `UploadConfig()` | Controls when Session Replay uploads data. Use `UploadConfig(disableMeteredUploads: true)` to pause uploads on metered networks (for example, cellular).                                                                                                                                         |

### Custom session IDs

Session Replay for iOS version 0.11.2 and later supports string session IDs, for example UUIDs, through the `customSessionId` property. Use a custom session ID if your project defines sessions with a custom event property instead of the Amplitude `session_id`.

When you set `customSessionId`, the value takes precedence over the session ID that the plugin syncs from the Amplitude SDK. Set the property to `nil` to resume using the Amplitude session ID.

```swift
// Keep a reference to the plugin to set the custom session ID
let sessionReplayPlugin = AmplitudeSwiftSessionReplayPlugin(sampleRate: 1.0)
sessionReplayPlugin.customSessionId = "ef197fc7-a46f-4e6c-a77f-8d90c17065c0"
amplitude.add(plugin: sessionReplayPlugin)

// Whenever your custom session changes
sessionReplayPlugin.customSessionId = NEW_CUSTOM_SESSION_ID
```

For Session Replay to match custom sessions reliably, custom session IDs must follow these constraints:

- The value can't contain `/`. Session Replay uses `/` as a delimiter in the session replay ID, which has the format `<deviceId>/<sessionId>`.
- The value can only contain the characters `a-z A-Z 0-9 _ - . | @ : =`.
- The value must match the session-defining property you send on events to Amplitude. For more information, refer to [Session matching](https://amplitude.com/docs/session-replay/session-matching).

### Remote configuration

Enable remote configuration to set Sample Rate and Masking Level in Amplitude. 

{% callout type="note" heading="Remote configuration and testing" %}
With `enableRemoteConfig` set to `true`, settings you define in Amplitude take precedence over settings you define locally in the SDK. For this reason, while testing your application, you should **disable** remote configuration to ensure you can set `sampleRate` to `1`, and ensure you capture test sessions.

{% /callout %}

### Block on-screen data

Session Replay supports three ways to block sensitive on-screen data. Masking setting for WebViews is in the [Web view support](#web-view-support-beta) section.

#### Mask level

Session Replay for iOS supports three levels of masking, configurable with the the `maskLevel` config option.

Use this option in the Session Replay configuration.

| Mask level | Description |
| ------| -----|
| `light` | Masks all passwords, email addresses, credit card numbers, and phone numbers.|
| `medium` | Masks all editable text views. |
| `conservative` | Masks all text views. | 

#### Privacy methods for UIKit

Session Replay provides an extension on `UIView` to manage privacy. Import the Session Replay library to access it.

```swift
import AmplitudeSessionReplay
```

| Variable             | Description                                                                                                                                                                                                                                                                                            |
|----------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `amp_isBlocked`      | Set `view.amp_isBlocked` to selectively replace a view and its subviews with a placeholder in session replays. UITextViews and UITextFields are automatically blocked. To unblock a view that is masked by default, set the this value to false  |                                                                          |

#### Privacy Modifiers for SwiftUI

Session Replay provides an extension on `View` to manage privacy. Import the Session Replay Library to access it.

```swift
import AmplitudeSessionReplay
```

| Modifier                          | Description                                                                                                                                  |
|-----------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------|
| `amp_setBlocked(_ blocked: Bool)` | Add the `amp_setBlocked()` modifier to a `View` to selectively replace a view and its subviews with a placeholder in session replays. To unblock a view that is masked by default, set the this value to false       |

### User opt-out

The Session Replay plugin follows the Amplitude-Swift SDK's `optOut` setting, and doesn't support user opt-outs on its own.

```swift
// Set optOut on the Amplitude SDK
let amplitude = Amplitude(configuration: Configuration(apiKey: API_KEY,
                                                           optOut: true,
                                                           /* other configuration */))
amplitude.add(plugin: AmplitudeSwiftSessionReplayPlugin(/* session replay options */))
```

### EU data residency

Session Replay is available to Amplitude Customers who use the EU data center. Set the `serverZone` configuration option to `EU` during initialization. For example:

```swift
// Set serverZone on the Amplitude SDK
let amplitude = Amplitude(configuration: Configuration(apiKey: API_KEY,
                                                           serverZone: .EU,
                                                           /* other configuration */))
amplitude.add(plugin: AmplitudeSwiftSessionReplayPlugin(/* session replay options */))
```

### Sampling rate

By default, Session Replay captures 0% of sessions for replay. Use the `sampleRate` configuration option to set the percentage of total sessions that Session Replay captures. For example:

To set the `sampleRate` consider the monthly quota on your Session Replay plan. For example, if your monthly quota is 2,500,000 sessions, and you average 3,000,000 monthly sessions, your quota is 83% of your average sessions. In this case, to ensure sampling lasts through the month, set `sampleRate` to `.83` or lower.

Keep the following in mind as you consider your sample rate:

- When you reach your monthly session quota, Amplitude stops capturing sessions for replay.
- Session quotas reset on the first of every month.
- Use sample rate to distribute your session quota over the course of a month, rather than using your full quota at the beginning of the month.
- To find the best sample rate, Amplitude recommends that you start low, for example `.01`. If this value doesn't capture enough replays, raise the rate over the course of a few days. For ways to monitor the number of session replays captured, see [View the number of captured sessions](https://amplitude.com/docs/session-replay#view-the-number-of-captured-sessions).
- Replays with [processing errors](https://amplitude.com/docs/session-replay/session-replay-plugin#troubleshooting) don't count toward your monthly quota. Replays with a retention error message have already been counted against the quota, when the session was still in the retention period.

```swift
// This configuration samples 1% of all sessions
amplitude.add(plugin: AmplitudeSwiftSessionReplayPlugin(sampleRate: 0.01))
```

### Recording quality

Choose a quality profile to balance replay fidelity with performance and storage. Lower profiles use a lower capture frame rate and lower image resolution. Higher profiles use a higher frame rate and higher resolution. Use `QualityProfile.automatic` to let the SDK select a profile based on the device (for example, high on newer devices, lower on older ones).

```swift
// Use automatic profile selection based on device
amplitude.add(plugin: AmplitudeSwiftSessionReplayPlugin(
    sampleRate: 0.1,
    quality: .automatic
))

// Or set a fixed profile (low, medium, or high)
amplitude.add(plugin: AmplitudeSwiftSessionReplayPlugin(
    sampleRate: 0.1,
    quality: .medium
))
```

### Disable uploads on metered networks

Avoid using the user's cellular data by pausing Session Replay uploads while the device is on a metered network. Session Replay still records data locally. Uploads resume when the device reconnects to Wi‑Fi or another non-metered connection.

```swift
// Set uploadConfig through the plugin's Config initializer
let config = AmplitudeSwiftSessionReplayPlugin.Config(
    sampleRate: 0.1,
    uploadConfig: UploadConfig(disableMeteredUploads: true)
)
amplitude.add(plugin: AmplitudeSwiftSessionReplayPlugin(config: config))
```

### Disable replay collection

After you enable Session Replay, it runs on your app until either:

- The user leaves your app.
- You call `sessionReplayPlugin.stop()`.
- You remove the plugin from the SDK with `amplitude.remove(plugin: sessionReplayPlugin)`.

Call `sessionReplayPlugin.stop()` before a user navigates to a restricted area of your app to disable replay collection while the user is in that area.

{% callout type="note" heading="Keep a reference" %}
This requires keeping a reference to the SessionReplayPlugin instance `let sessionReplayPlugin = AmplitudeSwiftSessionReplayPlugin(/* session replay options */)`.
{% /callout %}

Call `sessionReplayPlugin.start()` to re-enable replay collection when the user returns to an unrestricted area of your app.

To capture only specific screens, initialize the plugin with `autoStart: false` so it doesn't start on launch, then call `start()` and `stop()` as the user enters and leaves those screens:

```swift
// Add the plugin once, without starting capture
let sessionReplayPlugin = AmplitudeSwiftSessionReplayPlugin(sampleRate: 1.0, autoStart: false)
amplitude.add(plugin: sessionReplayPlugin)

// Start capture when the user enters a screen you want to record
sessionReplayPlugin.start()

// Stop capture when the user leaves that screen
sessionReplayPlugin.stop()
```

You can also use a feature-flag product such as [Amplitude Experiment](https://amplitude.com/docs/feature-experiment/overview) to create logic that enables or disables replay collection based on criteria such as location. For example, you can create a feature flag that targets a specific user group, and add that to your initialization logic:

```swift
import AmplitudeSwift
import AmplitudeSwiftSessionReplayPlugin

// Your existing initialization logic with Amplitude-Swift SDK
let amplitude = Amplitude(configuration: Configuration(apiKey: API_KEY,
                                                           /* other configuration */))

if (nonEUCountryFlagEnabled) {
  // Create and Install Session Replay Plugin
  let sessionReplayPlugin = AmplitudeSwiftSessionReplayPlugin(sampleRate: 0.1)
  amplitude.add(plugin: sessionReplayPlugin)
}
```

### Web view support (Beta)

By default, Session Replay blocks web views in a capture. To enable capture of all WebView components, set `captureWebViews` to `true` in the Session Replay configuration.

To mask specific WebView components, use the privacy methods described in [Block on-screen data](#block-on-screen-data).
```swift
// UIKit
webView.amp_isBlocked = false
```

### Map View Support (Alpha)

Session Replay supports capturing map views in iOS applications. To enable map view capture,  unmask the map view in your implementation.

```swift
// UIKit
mapView.amp_isBlocked = false

// SwiftUI
Map().amp_setBlocked(false)
```

### Log Recording

{% callout type="note" heading="Availability" %}
Log recording is available in AmplitudeSessionReplay `0.8.0` and later.
{% /callout %}

Session Replay supports recording logs in iOS applications. To enable log recording, send log messages through the `recordLog(level:message:date:)` API and configure the limits through `recordLogOptions` parameter while initializing the Session Replay plugin.

```swift
import AmplitudeSwiftSessionReplayPlugin

let sessionReplayPlugin = AmplitudeSwiftSessionReplayPlugin(recordLogOptions: .init(logCountThreshold: 2000, maxMessageLength: 4000))
amplitude.add(plugin: sessionReplayPlugin)

sessionReplayPlugin.recordLog(level: .error, message: "This is an error log")
```

If you have implemented a log system, you can make single-point modifications to integrate log recording functionality. See the following examples for more information.

#### CocoaLumberjack

If you use `CocoaLumberjack`, you can integrate it with a custom logger provider.

```swift
class AmplitudeLogRecordLogger: DDAbstractLogger {

    private weak var plugin: SessionReplayPlugin?

    init(_ plugin: SessionReplayPlugin) {
        self.plugin = plugin
    }

    override func log(message logMessage: DDLogMessage) {
        let recordLevel: RecordLogLevel
        switch logMessage.flag {
        case .error:
            recordLevel = .error
        case .warning:
            recordLevel = .warn
        case .info:
            recordLevel = .log
        default:
            return
        }
        plugin?.recordLog(level: recordLevel,
                          message: logMessage.message,
                          date: logMessage.timestamp)
    }
}

let sessionReplayPlugin = AmplitudeSwiftSessionReplayPlugin()
amplitude.add(plugin: sessionReplayPlugin)

DDLog.add(AmplitudeLogRecordLogger(sessionReplayPlugin))

```

#### React Native

If you use `console` log or `react-native-logs` with `consoleTransport`, you can integrate it with `RCTAddLogFunction`.
```swift
RCTAddLogFunction { level, source, fileName, lineNumber, message in
  let recordLevel: RecordLogLevel
  switch level {
  case .error:
    recordLevel = .error
  case .warning:
    recordLevel = .warn
  case .info:
    recordLevel = .log
  case .fatal:
    recordLevel = .error
  case .trace:
    recordLevel = .init("trace")
  default:
    return
  }
  self.sessionReplayPlugin.recordLog(level: recordLevel, message: message)
}
```

## Data retention, deletion, and privacy

Session replay uses existing Amplitude tools and APIs to handle privacy and deletion requests.
<!--vale off-->
{% callout type="note" heading="Consent management and Session Replay" %}
While privacy laws and regulations vary across states and countries, certain constants exist, including the requirements to disclose in a privacy notice the categories of personal information you are collecting, the purposes for its use, and the categories of third parties with which personal information is shared. When implementing a session replay tool, you should review your privacy notice to make sure your disclosures remain accurate and complete. And as a best practice, review your notice with legal counsel to make sure it complies with the constantly evolving privacy laws and requirements applicable to your business and personal information data practices.
{% /callout %}


### Retention period

If your Amplitude plan includes Session Replay, Amplitude retains raw replay data for 30 days from the date of ingestion. 

If you purchase extra session volume, Amplitude retains raw replay data for 90 days from the date of ingestion. If you need a more strict policy, contact Amplitude support to set the value to 30 days.

Changes to the retention period impact replays ingested after the change. Sessions captured and ingested before a retention period change retain the previous retention period.

Retention periods are set at the organization level. Replays that are outside of the retention period aren't viewable in Amplitude.

### DSAR API

The Amplitude [DSAR API](https://amplitude.com/docs/apis/analytics/ccpa-dsar) returns metadata about session replays, but not the raw replay data. All events that are part of a session replay include a `[Amplitude] Session Replay ID` event property. This event provides information about the sessions collected for replay for the user, and includes all metadata collected with each event.

```json
{
  "amplitude_id": 123456789,
  "app": 12345,
  "event_time": "2020-02-15 01:00:00.123456",
  "event_type": "first_event",
  "server_upload_time": "2020-02-18 01:00:00.234567",
  "device_id": "your device id",
  "user_properties": { ... }
  "event_properties": {
    "[Amplitude] Session Replay ID": "cb6ade06-cbdf-4e0c-8156-32c2863379d6/1699922971244"
  }
  "session_id": 1699922971244,
}
```

### Data deletion

Session Replay uses Amplitude's [User Privacy API](https://amplitude.com/docs/apis/analytics/user-privacy) to handle deletion requests. Successful deletion requests remove all session replays for the specified user.

When you delete the Amplitude project on which you use Session Replay, Amplitude deletes that replay data.

### Bot filter

Session Replay uses the same [block filter](https://amplitude.com/docs/data/block-bot-traffic) available in the Amplitude app. Session Replay doesn't block traffic based on event or user properties.

## Session Replay storage

If a user opts out tracking in your app, use the `optOut` configuration option to disable replay collection for that user.

Session Replay temporarily stores replay data data on the file system before it is uploaded. At every initialization, the least recent replays are trimmed to bring the total disk usage down to a maximum size.

## Known limitations

Keep the following limitations in mind as you implement Session Replay:

- Session Replay doesn't stitch together replays from a single user across multiple projects. For example:
  
    - You instrument multiple apps as separate Amplitude projects with Session Replay enabled in each.
    - A known user begins on one app, and then switch to another.
    - Amplitude captures both sessions.
    - The replay for each session is available for view in the corresponding host project.

- The User Sessions chart doesn't show session replays if your organization uses a custom session definition.

- Session Replay cannot capture the following iOS views:

    - Out-of-process iOS views, such as SFSafariViewController
    - AVPlayerLayer backed views
