이 페이지에서

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 저장소로 이동하십시오.

시작하기 전에

세션 리플레이 독립형 SDK를 사용하려면 다음이 필요합니다.

  1. 애플리케이션은 iOS 또는 iPadOS에서 실행됩니다.
  2. 타임스탬프 또는 SDK에 전달할 수 있는 사용자 지정 문자열 세션 ID를 사용하여 세션을 추적합니다. 세션 식별자가 변경될 때마다 SDK에 이를 알립니다.
  3. SDK에 장치 ID를 제공할 수 있습니다.
  4. 독립형 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은 동일한 기본 값에 대한 두 개의 뷰이며, SDK는 이를 문자열로 저장합니다.

  • sessionId 설정을 사용하면 현재 사용자 지정 세션 ID가 숫자 값으로 바뀝니다. 사용자 지정 세션 ID를 사용할 때는 세션이 변경될 때마다 sessionId 대신 customSessionId를 업데이트하십시오.
  • 저장된 값이 숫자가 아닌 경우 이 sessionId 속성은 -1을 반환합니다. 현재 값을 얻으려면 customSessionId를 읽으십시오.
  • 다른 값을 설정하면 현재 재생이 종료되고 새 재생이 시작됩니다.

세션 리플레이가 사용자 정의 세션을 안정적으로 일치시키려면 사용자 정의 세션 ID가 다음 제약 조건을 따라야 합니다.

  • 이 값은 /을 포함할 수 없습니다. 세션 리플레이는 /을 세션 리플레이 ID의 구분 기호로 사용하며, 형식은 <deviceId>/<sessionId>입니다.
  • 값에는 a-z A-Z 0-9 _ - . | @ : = 문자만 포함할 수 있습니다.
  • 이 값은 이벤트에 대해 Amplitude로 전송하는 세션 정의 속성과 일치해야 합니다. 자세한 내용은 세션 일치를 참조하십시오.

런타임 시 마스킹 변경

앱이 실행되는 동안 자동 마스킹 수준을 변경하려면 privacyConfig를 설정하세요.

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

원격 구성에서 마스킹 수준을 제공하는 경우 해당 수준이 우선합니다. SDK는 로컬 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 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.
  • Replays with processing errors 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
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()가 동일한 인스턴스에서 캡처를 재개하고 일시 중지하므로, 화면 전환 시 이를 호출하여 선택한 화면만 기록할 수 있습니다.

기록된 데이터 플러시

flush()를 호출하여 독립 실행형 SDK가 기록된 리플레이 데이터를 플러시하도록 요청하세요. 이 기능은 호스트 분석 클라이언트가 플러시되고 세션 리플레이를 동일한 지점에서 플러시하려는 경우에 유용합니다.

swift
sessionReplay.flush()

또한 Amplitude 실험과 같은 기능 플래그 제품을 사용하여 위치와 같은 기준에 따라 리플레이 수집을 활성화하거나 비활성화하는 로직을 만들 수도 있습니다. 예를 들어, 특정 사용자 그룹을 대상으로 하는 기능 플래그를 생성하고 이를 초기화 논리에 추가합니다.

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

Session replay uses existing Amplitude tools and APIs to handle privacy and deletion requests. <!--vale off-->

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.

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

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

이 내용이 도움이 되었나요?