このページでは

For AI agents: a documentation index is available at /docs/llms.txt. Append .md to any page URL for markdown, or send Accept: text/markdown.

セッションリプレイiOSスタンドアロンSDK

この記事では、スタンドアロンSDKを使用してiOS用セッションリプレイをインストールする方法について説明します。製品内アナリティクスにAmplitude以外のプロバイダーを使用している場合は、このオプションを選択してください。

アプリがすでにAmplitude iOS SDKを使用している場合は、代わりにセッションリプレイiOS SDKプラグインを使用してください。

Analytics-Swift SDKとAmplitude(アクション)の送信先経由でセグメントを使用する場合は、セグメントプラグインを選択してください。

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.

問題の報告

iOS用セッションリプレイに関する問題を報告される場合は、AmplitudeSessionReplay-ios GitHubリポジトリにアクセスしてください。

始める前に

Session Replay Standalone SDKには以下が必要です。

  1. アプリケーションは iOS または iPadOS 上で実行されます。
  2. タイムスタンプまたはカスタム文字列セッションIDを使用してセッションを追跡しており、SDKに渡すことができること。セッション識別子が変更されるたびに、SDKに通知します。
  3. デバイスIDをSDKに提供できること。
  4. Standalone SDKに渡すSession IDおよびDevice IDが、Amplitudeにイベントプロパティとして送信されるものと一致していること。

スタンドアロンSDKはセッション管理を提供しません。アプリケーションまたはサードパーティの連携で、Session IDおよびDevice IDに対する変更を反映してSDKを更新する必要があります。

Supported iOS versions

Session Replay supports a minimum target version of iOS 13.

クイックスタート

最新バージョンのセッションリプレイを、プロジェクトの依存関係に追加します。

セッションリプレイをPackage.swiftファイルの依存関係として追加するか、Xcodeのパッケージリストに含めます。

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

サードパーティのアナリティクスと統合するには、AmplitudeSessionReplayターゲットを使用します。

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

アプリケーションコードを設定します。

  1. SessionReplayインスタンスを作成します。APIキーと、セッション識別子およびデバイス識別子(使用可能な場合)を渡します。
  2. リプレイのキャプチャを開始するためにsessionReplay.start()を呼び出します。スタンドアロンSDKは自動的にキャプチャを開始しません。そのため、デバイス識別子とセッション識別子を設定したらstart()を呼び出す必要があります。
  3. セッションまたはデバイス識別子が変更された場合は、sessionReplay.sessionId(セッション)またはsessionReplay.deviceId(デバイス)を使用して新しい値をAmplitudeに渡します。文字列のセッションIDの場合は、代わりにsessionReplay.customSessionIdを使用します。カスタムセッション ID を参照してください。
  4. sessionReplay.additionalEventPropertiesを使用してセッションリプレイのプロパティを収集し、他のイベントプロパティと一緒に送信します。
swift
import AmplitudeSessionReplay
import ThirdPartyAnalytics
// Initialize the standalone session replay SDK
let sessionReplay = SessionReplay(apiKey: amplitude.apiKey,
                                     deviceId: DEVICE_ID,
                                     sessionId: SESSION_ID,
                                     sampleRate: 0.1)
// Start capturing replays. The standalone SDK doesn't start automatically.
sessionReplay.start()
// Track an event
// Get session replay properties for this session
var eventProperties = event.eventProperties ?? [:]
eventProperties.merge(sessionReplay.additionalEventProperties) { (current, _) in current }
event.eventProperties = eventProperties
ThirdPartyAnalytics.track(event)
// Handle session ID changes
// Whenever the session ID changes
ThirdPartyAnalytics.setSessionId(sessionId)
// Update the session ID in session replay
sessionReplay.sessionId = ThirdPartyAnalytics.getSessionId()
// Handle device ID changes
// Whenever the device ID changes
ThirdPartyAnalytics.setDeviceId(deviceId)
// Update the device ID in session replay
sessionReplay.deviceId = ThirdPartyAnalytics.getDeviceId()

設定

セッションリプレイ SDK を初期化する際に、次の設定オプションを渡します。

カスタムセッションID

iOSバージョン0.11.2以降のセッションリプレイでは、customSessionIdプロパティを通じて文字列セッションID(UUIDなど)をサポートしています。プロジェクトでタイムスタンプベースのsession_idではなくカスタムイベントプロパティを使用してセッションを定義している場合は、カスタムセッションIDを使用してください。

初期化子は数値のsessionIdのみを受け入れます。文字列値を使用するには、インスタンスを作成した後にそのインスタンスでcustomSessionIdを設定し、カスタムセッションが変更される度に更新します。

swift
let sessionReplay = SessionReplay(apiKey: API_KEY,
                                     deviceId: DEVICE_ID,
                                     sampleRate: 0.1)
// Set a string session ID instead of the numeric sessionId
sessionReplay.customSessionId = "ef197fc7-a46f-4e6c-a77f-8d90c17065c0"
sessionReplay.start()
// Whenever your custom session changes
sessionReplay.customSessionId = ThirdPartyAnalytics.getCustomSessionId()

sessionIdとcustomSessionIdは同じ基本値の2つのビューであり、SDKはその値を文字列として保存します。

  • sessionIdを設定すると、現在のカスタムセッションIDが数値に置き換えられます。カスタムセッションIDを使用する場合は、セッションが変更される度にsessionIdではなくcustomSessionIdを更新してください。
  • 格納されている値が数値でない場合、sessionIdプロパティは-1を返します。現在の値を取得するには、customSessionIdを読み込みます。
  • 別の値を設定すると、現在の再生が終了し、新しい再生が開始されます。

セッションリプレイがカスタムセッションと確実に一致するためには、カスタムセッションIDは次の制約に従う必要があります。

  • この値に/を含めることはできません。セッションリプレイは/をセッションリプレイIDの区切り文字として使用します。このIDの形式は<deviceId>/<sessionId>です。
  • この値に使用できるのは、文字a-z A-Z 0-9 _ - . | @ : =のみです。
  • 値は、イベント時にAmplitudeに送信するセッション定義プロパティと一致している必要があります。 詳細については、セッションの照合を参照してください。

実行時にマスキングを変更

アプリの実行中に自動マスキングレベルを変更するようにprivacyConfig設定します。

swift
sessionReplay.privacyConfig = PrivacyConfig(maskLevel: .conservative)

リモート設定がマスクレベルを指定している場合、そのレベルが優先されます。 SDK はローカル値を保持し、Remote Config がマスキングレベルを提供しない場合や、Remote Config を無効にした場合privacyConfigに適用します。

Remote configuration

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

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.

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 section.

Mask level

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

Use this option in the Session Replay configuration.

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

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

ユーザーのオプトアウト

セッションリプレイにはオプトアウト設定オプションがあります。初期化中にoptOut: trueを渡すと、Amplitudeはセッションリプレイを収集しません。例えば:

swift
// Pass a boolean value to indicate a user's opt-out status
        let sessionReplay = SessionReplay(apiKey: API_KEY,
                                             optOut: true,
                                             /* other 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 to EU
let sessionReplay = SessionReplay(apiKey: API_KEY,
                                     serverZone: .EU,
                                     /* other session replay options */)

Sampling rate

By default, Session Replay captures 0% of sessions for replay. Use your SDK's sampleRate configuration option to set the proportion of sessions to capture.

For manual and dynamic sampling, quota planning, and quota accounting, go to Configure Session Replay sampling.

swift
// This configuration samples 1% of all sessions
let sessionReplay = SessionReplay(apiKey: API_KEY,
                                     sampleRate: 0.01,
                                     /* other session replay options */)

録画品質

再生の忠実度と、パフォーマンスおよびストレージのバランスを調整するには、品質プロファイルを選択します。低いプロファイルでは、キャプチャフレームレートと画像解像度が低くなります。プロファイルが高いほど、使用されるフレームレートと解像度も高くなります。 SDKがデバイスに基づいてプロファイルを選択できるようにする場合は、QualityProfile.automaticを使用します(例:新しいデバイスでは高く、古いデバイスでは低くするなど)。

swift
// Use automatic profile selection based on device
let sessionReplay = SessionReplay(apiKey: API_KEY,
                                     deviceId: DEVICE_ID,
                                     sessionId: SESSION_ID,
                                     quality: .automatic,
                                     /* other session replay options */)
// Or set a fixed profile (low, medium, or high)
let sessionReplay = SessionReplay(apiKey: API_KEY,
                                     deviceId: DEVICE_ID,
                                     sessionId: SESSION_ID,
                                     quality: .medium,
                                     /* other session replay options */)

既存のスタンドアロン・インスタンスのプロファイルを変更することもできます。

swift
sessionReplay.quality = .medium

従量課金制ネットワークでのアップロードを無効にする

デバイスが従量課金制ネットワークに接続されている間は、セッションリプレイのアップロードを一時停止し、ユーザーのモバイルデータの使用を避けてください。セッションリプレイは引き続きデータをローカルに記録します。デバイスがWi-Fi、またはその他の従量制ではない接続に再接続されると、アップロードが再開されます。

swift
let sessionReplay = SessionReplay(apiKey: API_KEY,
                                     deviceId: DEVICE_ID,
                                     sessionId: SESSION_ID,
                                     uploadConfig: UploadConfig(disableMeteredUploads: true),
                                     /* other session replay options */)

リプレイ収集を無効にする

セッションリプレイを有効にした後は、次のいずれかの条件までアプリ上で実行されます。

  • ユーザーがアプリを離れる。
  • sessionReplay.stop()呼び出します。

ユーザーがアプリの制限付きエリアに移動する前にsessionReplay.stop()を呼び出して、ユーザーがそのエリアにいる間のリプレイ収集を無効にします。

ユーザーがアプリの制限のないエリアに戻ったときに、sessionReplay.start()を呼び出してリプレイ収集を再度有効にします。start()およびstop()は同じインスタンス上でキャプチャの再開と一時停止を行うため、画面の切り替え時にこれらを呼び出すことで、選択した画面のみを録画することができます。

記録されたデータをフラッシュする

スタンドアロン SDK に記録されたリプレイデータをフラッシュするよう要求するには、flush()を呼び出します。 これは、ホストアナリティクスクライアントがフラッシュされるときに、同時にセッションリプレイをフラッシュしたい場合に便利です。

swift
sessionReplay.flush()

また、Amplitude Experimentなどのフィーチャーフラグプロダクトを使用して、場所などの基準に基づいてリプレイ収集を有効または無効にするロジックを作成することもできます。たとえば、特定のユーザーグループを対象とするフィーチャーフラグを作成し、それを初期化ロジックに追加します。

swift
import AmplitudeSessionReplay
import ThirdPartyAnalytics
let sessionReplay = SessionReplay(apiKey: amplitude.apiKey,
                                     deviceId: DEVICE_ID,
                                     sessionId: SESSION_ID,
                                     sampleRate: 1.0)
if (nonEUCountryFlagEnabled) {
    sessionReplay.start()
}

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.

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

Availability

AmplitudeSessionReplay 0.8.0 and later support log recording.

Session Replay supports recording logs in iOS applications. Configure the limits with recordLogOptions when you initialize the integration, then send log messages through recordLog(level:message:date:).

import AmplitudeSessionReplay

let sessionReplay = SessionReplay(
    apiKey: API_KEY,
    recordLogOptions: .init(logCountThreshold: 2000, maxMessageLength: 4000)
)

sessionReplay.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

Review consent guidance when you implement capture.

Retention period

For native and Flutter SDK retention guidance and the effective date of changes, go to the Session Replay data lifecycle reference.

DSAR API

For replay metadata returned by the DSAR API, go to Session Replay DSAR metadata.

Data deletion

For user and project deletion behavior, go to Session Replay data deletion.

Bot filter

For bot filtering and property-filter restrictions, go to Session Replay bot filtering.

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

Troubleshooting

For more information about individual statuses and errors, see the Session Replay Ingestion Monitor.

Multiple Amplitude instances

Session Replay supports attaching to a single instance of the Amplitude SDK. If you have more than one instance instrumented in your application, make sure to start Session Replay on the instance that most relates to your project.

Replay length and session length don't match

In some scenarios, the length of a replay may exceed the time between the [Amplitude] Start Session and [Amplitude] End Session events. This happens when a user closes the [Amplitude] End Session occurs, but before the iOS SDK and Session Replay middleware can process it. When the user uses the app again, the SDK and middleware process the event and send it to Amplitude, along with the replay. You can verify this scenario occurs if you see a discrepancy between the End Session Client Event Time and the Client Upload Time.

Session replays don't appear in Amplitude

Session replays may not appear in Amplitude due to:

  • Lack of connectivity
  • No events triggered through the iOS SDK in the current session
  • Sampling

Lack of connectivity

Ensure your app has access to the internet then try again.

No events triggered through the iOS SDK in the current session

Session Replay requires that at least one event in the user's session has the [Amplitude] Session Replay ID property. If you instrument your events with an analytics provider other than Amplitude, the iOS SDK may send only the default Session Start and Session End events, which don't include this property.

For local testing, you can force a Session Start event to ensure that Session Replay functions.

  1. In Amplitude, in the User Lookup Event Stream, you should see a Session Start event that includes the [Amplitude] Session Replay ID property. After processing, the Play Session button should appear for that session.

Sampling

As mentioned above, the default sampleRate for Session Replay is 0. Update the rate to a higher number. For more information see, Sampling rate.

Some sessions don't include the Session Replay ID property

Session replay doesn't require that all events in a session have the [Amplitude] Session Replay ID property, only that one event in the session has it. Reasons why [Amplitude] Session Replay ID may not be present in an event include:

  • The user may have opted out or the session may not be part of the sample set given the current sampleRate. Increasing the sampleRate captures more sessions.
  • Amplitude events may still send through your provider, but additionalEventProperties doesn't return the [Amplitude] Session Replay ID property. This can result from optOut and sampleRate configuration settings. Check that optOut and sampleRate are set to include the session.

Session Replay processing errors

In general, replays should be available within minutes of ingestion. Delays or errors may be the result of one or more of the following:

  • Mismatching API keys or Device IDs. This can happen if Session Replay and standard event instrumentation use different API keys or Device IDs.
  • Session Replay references the wrong project.
  • Short sessions. If a users bounces within a few seconds of initialization, the SDK may not have time to upload replay data.
  • Replays older than the set retention period (defaults to 90 days).

Report an Issue

If you encounter any issues with Session Replay that aren't covered in the troubleshooting guide above, please report them on our GitHub repository.

When creating an issue, please include:

  • A clear description of the problem
  • Steps to reproduce the issue
  • Expected vs actual behavior
  • SDK version you're using
  • Any relevant error messages or logs

これは役に立ちましたか?