### Initialize AmplitudeContext Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/INDEX.md Minimal setup requires only an API key. Full setup allows for instance naming, server zone selection, and custom logger configuration. ```swift // Minimal setup let context = AmplitudeContext(apiKey: "your-key") ``` ```swift // Full setup let context = AmplitudeContext( apiKey: "your-key", instanceName: "my_app", serverZone: .EU, logger: OSLogger(logLevel: .debug) ) ``` -------------------------------- ### Setup Plugin with Analytics Client Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/api-reference/plugin-system.md Implement the `setup` method to initialize plugin state or subscribe to updates when the plugin is attached to the analytics client. It receives the analytics client and SDK context. ```swift func setup(analyticsClient: any AnalyticsClient, amplitudeContext: AmplitudeContext) ``` ```swift class CustomPlugin: UniversalPlugin { var name: String? = "CustomPlugin" func setup(analyticsClient: any AnalyticsClient, amplitudeContext: AmplitudeContext) { amplitudeContext.logger.debug(message: "Plugin initialized") } // ... other methods } ``` -------------------------------- ### Minimal AmplitudeContext Setup Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/configuration.md Use this minimal setup when only the API key is provided, relying on default values for all other parameters. ```swift // Minimal setup (uses all defaults except API key) let context = AmplitudeContext(apiKey: "abc123xyz") ``` -------------------------------- ### Minimal SDK Initialization Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/integration-guide.md Initialize AmplitudeCore with the minimum required API key. This is the simplest way to get started. ```swift import AmplitudeCore let context = AmplitudeContext(apiKey: "your-api-key") ``` -------------------------------- ### Crash Detection Setup Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/MANIFEST.txt Demonstrates how to enable and configure crash detection. Ensure the necessary permissions and configurations are in place. ```swift amplitude.diagnostics.enableCrashDetection() amplitude.diagnostics.setCrashCallback { crashInfo in print("Crash detected: \(crashInfo)") } ``` -------------------------------- ### Basic Initialization Example Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/api-reference/amplitude-context.md Demonstrates the simplest way to create an AmplitudeContext instance using only the mandatory API key. ```swift let context = AmplitudeContext(apiKey: "abc123xyz") ``` -------------------------------- ### Development Setup for Amplitude Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/configuration.md Configure the Amplitude SDK for a development environment with verbose logging enabled. ```swift let logger = OSLogger(logLevel: .debug) let context = AmplitudeContext( apiKey: "dev-api-key", instanceName: "dev", serverZone: .US, logger: logger ) ``` -------------------------------- ### ServerZone Usage Example Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/types.md Shows how to configure an AmplitudeContext with a specific ServerZone, such as the European Union data center. ```swift let context = AmplitudeContext( apiKey: "key", serverZone: .EU // Use European servers ) ``` -------------------------------- ### LogLevel Comparison Example Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/api-reference/logger.md Demonstrates how to filter logs based on the current log level using the Comparable conformance. ```swift if logLevel >= logger.logLevel { // Log this message } ``` -------------------------------- ### Plugin Lifecycle Example Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/api-reference/plugin-system.md Demonstrates the implementation of a custom plugin, 'EnrichmentPlugin', showing how to set up, execute event modifications, handle identity changes, and tear down. ```swift class EnrichmentPlugin: UniversalPlugin { var name: String? { "EnrichmentPlugin" } private weak var analyticsClient: (any AnalyticsClient)? func setup(analyticsClient: any AnalyticsClient, amplitudeContext: AmplitudeContext) { self.analyticsClient = analyticsClient amplitudeContext.logger.debug(message: "Enrichment plugin ready") } func execute(_ event: inout Event) { // Add custom properties to every event var props = event.eventProperties ?? [:] props["custom_field"] = "custom_value" props["app_version"] = "1.0.0" event.eventProperties = props } func onIdentityChanged(_ identity: AnalyticsIdentity) { if let userId = identity.userId { // Handle user identification } } func teardown() { // Cleanup } } ``` -------------------------------- ### Plugin Setup and Remote Config Subscription (Swift) Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/integration-guide.md Implement the UniversalPlugin protocol to set up your plugin. Subscribe to remote configurations to dynamically update plugin behavior. ```swift class MyPlugin: UniversalPlugin { var name: String? { "MyPlugin" } weak var analyticsClient: (any AnalyticsClient)? var context: AmplitudeContext? func setup(analyticsClient: any AnalyticsClient, amplitudeContext: AmplitudeContext) { self.analyticsClient = analyticsClient self.context = amplitudeContext amplitudeContext.logger.debug(message: "Plugin initialized") // Subscribe to remote config amplitudeContext.remoteConfigClient.subscribe( key: "myPlugin.config", callback: { config, source, date in self.updateConfig(config) } ) } func teardown() { // Cleanup resources } private func updateConfig(_ config: RemoteConfigClient.RemoteConfig?) { // Update plugin behavior based on remote config } } ``` -------------------------------- ### Track Event Usage Examples Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/api-reference/plugin-system.md Illustrates how to use the `track` method to record events, with and without custom properties. ```swift // Event without properties analyticsClient.track(eventType: "page_view", eventProperties: nil) ``` ```swift // Event with properties analyticsClient.track(eventType: "purchase", eventProperties: [ "product_id": "sku_123", "price": 29.99, "currency": "USD" ]) ``` -------------------------------- ### Create InterfaceChangeSignal Instance Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/api-reference/interface-signals.md Example of how to create and initialize an InterfaceChangeSignal object. ```swift let signal = InterfaceChangeSignal(time: Date()) ``` -------------------------------- ### Production Setup for Amplitude (US) Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/configuration.md Configure the Amplitude SDK for a production environment in the US region, with error-level logging. ```swift let context = AmplitudeContext( apiKey: "prod-api-key", instanceName: "production", serverZone: .US, logger: OSLogger(logLevel: .error) ) ``` -------------------------------- ### Amplitude Swift Diagnostics Usage Example Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/api-reference/diagnostics.md Demonstrates how to initialize the diagnostics client, set tags, record metrics and events, check for crashes, and manually flush data. ```swift let context = AmplitudeContext(apiKey: "your-api-key") // Set tags await context.diagnosticsClient.setTags([ "build_config": "release", "feature_flag_enabled": "true" ]) // Record metrics await context.diagnosticsClient.increment(name: "api_calls", size: 1) await context.diagnosticsClient.recordHistogram(name: "api_latency_ms", value: 125.5) // Record events await context.diagnosticsClient.recordEvent( name: "sync_completed", properties: ["event_count": 42] ) // Check for crash if await context.diagnosticsClient.didLastRunCrash { let crash = CrashCatcher.consumePreviousCrash() print("Crash report: \(crash ?? \"unknown\")") } // Flush manually (usually automatic) await context.diagnosticsClient.flush() // Static check (before SDK init) if DiagnosticsClient.didLastRunCrash { print("Previous session crashed") } ``` -------------------------------- ### Retrieve a Plugin by Name Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/api-reference/plugin-system.md Use this method to get a specific plugin instance from the PluginHost using its string name. Ensure the plugin is installed before attempting retrieval. ```swift func plugin(name: String) -> UniversalPlugin? ``` ```swift if let plugin = pluginHost.plugin(name: "SessionReplay") { print("Session replay plugin found") } ``` -------------------------------- ### Plugin Implementation Example Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/MANIFEST.txt Illustrates the implementation of a custom plugin for the Amplitude SDK. Plugins can be used to intercept, modify, or augment events. ```swift class MyPlugin: AmplitudePlugin { func setup(amplitude: AmplitudeInstance) throws {} func execute(event: AmplitudeEvent) -> AmplitudeEvent? { var modifiedEvent = event modifiedEvent.eventProperties?["plugin_added"] = true return modifiedEvent } } let plugin = MyPlugin() let amplitude = AmplitudeContext(configuration: configuration) amplitude.addPlugin(plugin) ``` -------------------------------- ### Production Setup for Amplitude (EU - GDPR) Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/configuration.md Configure the Amplitude SDK for a production environment in the EU, adhering to GDPR, with error-level logging. ```swift let context = AmplitudeContext( apiKey: "prod-api-key-eu", instanceName: "production_eu", serverZone: .EU, logger: OSLogger(logLevel: .error) ) ``` -------------------------------- ### Initialize AmplitudeContext with Custom Configuration Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/api-reference/amplitude-context.md Initialize AmplitudeContext with custom settings for instance name, server zone, and logger. Useful for multi-instance setups or specific logging requirements. ```swift let context = AmplitudeContext( apiKey: "your-api-key", instanceName: "analytics", serverZone: .EU, logger: OSLogger(logLevel: .debug) ) ``` -------------------------------- ### Mock Implementation for Testing Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/MANIFEST.txt Provides an example of creating a mock Amplitude instance for testing purposes. This allows you to isolate and test components that interact with the SDK. ```swift class MockAmplitude: AmplitudeInstance { var trackCalled = false override func track(eventName: String, eventProperties: [String : Any]? = nil, options: EventOptions? = nil) { trackCalled = true } } let mockAmplitude = MockAmplitude(configuration: configuration) // Use mockAmplitude in your tests ``` -------------------------------- ### Event Enrichment Example Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/MANIFEST.txt Demonstrates how to enrich an event with additional properties before it is tracked. This is typically done within a plugin. ```swift func execute(event: AmplitudeEvent) -> AmplitudeEvent? { var modifiedEvent = event modifiedEvent.eventProperties?["user_id"] = "user123" return modifiedEvent } ``` -------------------------------- ### Lazy Plugin Initialization in Swift Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/integration-guide.md Defer expensive plugin initialization until it's actually needed. This improves startup performance by delaying heavy setup tasks. ```swift class LazyPlugin: UniversalPlugin { var name: String? { "LazyPlugin" } private var isInitialized = false func setup(analyticsClient: any AnalyticsClient, amplitudeContext: AmplitudeContext) { // Defer expensive initialization Task.detached { await self.performHeavyInitialization() self.isInitialized = true } } func execute(_ event: inout Event) { // Quick check before expensive operations guard isInitialized else { return } // Process event } private func performHeavyInitialization() async { // Load resources, etc. } } ``` -------------------------------- ### Error Handling Example Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/MANIFEST.txt Illustrates how to handle errors that may occur during SDK operations. It's recommended to use a try-catch block or check error results. ```swift do { try amplitude.track(eventName: "test_event") } catch { print("Error tracking event: \(error)") } ``` -------------------------------- ### Amplitude Swift Diagnostics Remote Configuration JSON Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/api-reference/diagnostics.md Example JSON structure for configuring diagnostics remotely via the 'diagnostics.iosSDK' key. ```json { "enabled": true, "sampleRate": 0.1, "availabilities": { "CrashTracking": "1.4.0" } } ``` -------------------------------- ### Diagnostics Recording Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/MANIFEST.txt Example of recording diagnostic information. This can be used for debugging and performance monitoring. ```swift amplitude.diagnostics.record(metric: "custom_metric", value: 100) ``` -------------------------------- ### Interface Signal Handling Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/MANIFEST.txt Example of handling application lifecycle signals. This allows the SDK to react to events like app backgrounding or foregrounding. ```swift amplitude.interfaceSignals.applicationDidEnterBackground() amplitude.interfaceSignals.applicationWillEnterForeground() ``` -------------------------------- ### Record Session Start Event Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/integration-guide.md Record a 'session_started' event with properties indicating whether the user ID was provided. This follows the setting of diagnostic tags. ```swift await diagnostics.recordEvent( name: "session_started", properties: ["user_id_provided": false] ) ``` -------------------------------- ### Configure Sampling Rate Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/integration-guide.md Subscribe to remote configuration to dynamically update the analytics sampling rate. This example extracts a 'sampleRate' value from the configuration. ```swift override func setup(analyticsClient: any AnalyticsClient, amplitudeContext: AmplitudeContext) { super.setup(analyticsClient: analyticsClient, amplitudeContext: amplitudeContext) amplitudeContext.remoteConfigClient.subscribe( key: "myAnalytics.iosSDK.sampling", callback: { config, source, date in if let config = config as? [String: Any], let sampleRate = config["sampleRate"] as? Double { self.updateSampleRate(sampleRate) } } ) } func updateSampleRate(_ rate: Double) { sampleRate = max(0, min(1, rate)) } ``` -------------------------------- ### Integrating Provider and Receiver Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/api-reference/interface-signals.md Demonstrates how to instantiate and connect a custom InterfaceSignalProvider with an InterfaceSignalReceiver. The receiver is registered with the provider to start receiving notifications. ```swift let provider = AppLifecycleProvider() let plugin = SessionReplayPlugin() // Register plugin to receive interface signals provider.addInterfaceSignalReceiver(plugin) // Plugin now receives onStartProviding, onInterfaceChanged, onStopProviding calls ``` -------------------------------- ### Custom AppLifecycleProvider Implementation Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/api-reference/interface-signals.md An example implementation of an InterfaceSignalProvider that listens to UIApplication lifecycle notifications and forwards them to registered receivers. It manages receiver registration and notification tokens. ```swift class AppLifecycleProvider: InterfaceSignalProvider { private var receivers: [InterfaceSignalReceiver] = [] private var notificationTokens: [NSObjectProtocol] = [] var isProviding: Bool { !receivers.isEmpty } func addInterfaceSignalReceiver(_ receiver: any InterfaceSignalReceiver) { receivers.append(receiver) if receivers.count == 1 { // Start listening to app lifecycle events let foregroundToken = NotificationCenter.default.addObserver( forName: UIApplication.didBecomeActiveNotification, object: nil, queue: .main ) { _ in self.notifyForegrounded() } notificationTokens.append(foregroundToken) let backgroundToken = NotificationCenter.default.addObserver( forName: UIApplication.didEnterBackgroundNotification, object: nil, queue: .main ) { _ in self.notifyBackgrounded() } notificationTokens.append(backgroundToken) receivers.forEach { $0.onStartProviding() } } } func removeInterfaceSignalReceiver(_ receiver: any InterfaceSignalReceiver) { receivers.removeAll { $0 === receiver } if receivers.isEmpty { // Stop listening notificationTokens.forEach(NotificationCenter.default.removeObserver(_:)) notificationTokens.removeAll() } } private func notifyForegrounded() { let signal = InterfaceChangeSignal(time: Date()) receivers.forEach { $0.onInterfaceChanged(signal: signal) } } private func notifyBackgrounded() { let signal = InterfaceChangeSignal(time: Date()) receivers.forEach { $0.onInterfaceChanged(signal: signal) } } } ``` -------------------------------- ### plugin(name:) Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/api-reference/plugin-system.md Retrieves a specific plugin installed in the PluginHost by its unique name. This is useful for accessing and interacting with a known plugin instance. ```APIDOC ## plugin(name:) ### Description Retrieves a plugin by name. ### Method func plugin(name: String) -> UniversalPlugin? ### Parameters #### Path Parameters - **name** (String) - Required - Name of the plugin to retrieve ### Returns - **UniversalPlugin?** - The plugin if found, nil otherwise ### Usage ```swift if let plugin = pluginHost.plugin(name: "SessionReplay") { print("Session replay plugin found") } ``` ``` -------------------------------- ### Validate Version String Comparisons Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/errors.md Provides examples of valid and invalid version string comparisons using isGreaterThanOrEqualToVersion. Invalid formats trigger specific VersionError cases. ```swift try "1.4.7".isGreaterThanOrEqualToVersion("1.4.0") // ✓ valid try "1".isGreaterThanOrEqualToVersion("2") // ✓ valid try "1.4".isGreaterThanOrEqualToVersion("1.4.0") // ✓ valid try "".isGreaterThanOrEqualToVersion("1.0") // ✗ throws .emptyVersionString try ".1.4".isGreaterThanOrEqualToVersion("1.0") // ✗ throws .invalidVersionString try "1.4.".isGreaterThanOrEqualToVersion("1.0") // ✗ throws .invalidVersionString try "1..4".isGreaterThanOrEqualToVersion("1.0") // ✗ throws .invalidVersionString try "1.4 .0".isGreaterThanOrEqualToVersion("1.0") // ✗ throws .invalidVersionString try "1.4.a".isGreaterThanOrEqualToVersion("1.0") // ✗ throws .invalidVersionString ``` -------------------------------- ### Register Receiver with Provider Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/api-reference/interface-signals.md Example of adding a receiver to an AppLifecycleProvider to get interface change notifications. ```swift let provider = AppLifecycleProvider() provider.addInterfaceSignalReceiver(mySessionReplayPlugin) ``` -------------------------------- ### AmplitudeContext Initialization Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/MANIFEST.txt Demonstrates basic initialization of the AmplitudeContext. Ensure you have the necessary configuration and dependencies set up. ```swift let amplitude = AmplitudeContext(configuration: configuration) ``` -------------------------------- ### Unregister Receiver from Provider Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/api-reference/interface-signals.md Example of removing a receiver from a provider to stop receiving interface change notifications. ```swift provider.removeInterfaceSignalReceiver(mySessionReplayPlugin) ``` -------------------------------- ### Initialize AmplitudeContext Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/api-reference/amplitude-context.md Create a basic AmplitudeContext instance with the required API key. This is the most common way to initialize the SDK. ```swift let context = AmplitudeContext(apiKey: "your-api-key") ``` -------------------------------- ### CrashCatcher.consumePreviousCrash() Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/api-reference/utilities.md Atomically retrieves and clears the crash report from the previous session. Only the first caller gets the data. ```APIDOC ## CrashCatcher.consumePreviousCrash() ### Description Atomically retrieves and clears the crash report from the previous session. Only the first caller gets data. ### Returns `String?` — Crash report text or nil if no crash or already consumed ### Usage ```swift if let report = CrashCatcher.consumePreviousCrash() { print("Crash report: \(report)") // Send to backend } ``` ``` -------------------------------- ### Initialize with EU Server Zone Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/api-reference/amplitude-context.md Shows how to configure AmplitudeContext to use the European data center by specifying the `.EU` server zone. ```swift let context = AmplitudeContext( apiKey: "abc123xyz", serverZone: .EU ) ``` -------------------------------- ### Sampling Implementation Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/MANIFEST.txt Illustrates how to implement deterministic sampling for events. This helps control the volume of data sent to Amplitude. ```swift let sampled = amplitude.utilities.isDeterministicSampled(userId: "user123", eventType: "purchase", sampleRate: 0.5) if sampled { // Track the event } ``` -------------------------------- ### Initialize with Custom Logger Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/api-reference/amplitude-context.md Illustrates initializing AmplitudeContext with a custom logger instance, allowing for more granular control over log levels and output. ```swift let logger = OSLogger(logLevel: .debug) let context = AmplitudeContext( apiKey: "abc123xyz", logger: logger ) // Log messages logger.debug(message: "Initialization complete") ``` -------------------------------- ### Get All Diagnostic Tags Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/api-reference/diagnostics.md Retrieves all currently set diagnostic tags as a dictionary. This can be used to inspect all metadata associated with diagnostics. ```swift let allTags = await diagnosticsClient.getTags() print("All diagnostic tags: \(allTags)") ``` -------------------------------- ### Subscribe with Immediate Callback Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/api-reference/remote-config.md Subscribe to configuration updates using `.all` delivery mode for immediate callback from cache, followed by remote if available. ```swift // Immediate callback (cache then remote) remoteConfigClient.subscribe(key: "myConfig", deliveryMode: .all) { config, source, date in print("Got config from \(source)") } ``` -------------------------------- ### RemoteConfigClient Initialization Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/api-reference/remote-config.md Initializes a RemoteConfigClient to fetch configurations from Amplitude servers. It requires an API key, server zone, and a logger. An optional instance name can be provided for caching. ```APIDOC ## Public Initializer ### Description Creates a `RemoteConfigClient` that automatically fetches configuration from the appropriate Amplitude server. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **apiKey** (`String`) - Required - Amplitude API key for authentication - **serverZone** (`ServerZone`) - Required - Server region (`.US` or `.EU`) - **instanceName** (`String?`) - Optional - Optional identifier for caching (multiple instances can exist) - **logger** (`CoreLogger`) - Required - Logger for diagnostic messages ### Returns `RemoteConfigClient` ### Usage Example ```swift let logger = OSLogger(logLevel: .debug) let configClient = RemoteConfigClient( apiKey: "abc123xyz", serverZone: .US, instanceName: "main_app", logger: logger ) ``` ``` -------------------------------- ### Full SDK Configuration Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/integration-guide.md Configure AmplitudeCore with advanced options like server zone, custom instance names, and logging. Access remote config and diagnostics clients after initialization. ```swift let logger = OSLogger(logLevel: .debug) let context = AmplitudeContext( apiKey: "your-api-key", instanceName: "my_analytics", serverZone: .EU, logger: logger ) // Access remote config let configClient = context.remoteConfigClient // Access diagnostics let diagnosticsClient = context.diagnosticsClient ``` -------------------------------- ### Initialize and Subscribe to Diagnostics Configuration Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/api-reference/remote-config.md Initialize the RemoteConfigClient with an API key, server zone, and logger. Then, subscribe to the 'diagnostics.iosSDK' key to receive and process configuration updates for diagnostics. ```swift let configClient = RemoteConfigClient( apiKey: "your-api-key", serverZone: .US, logger: OSLogger(logLevel: .debug) ) configClient.subscribe(key: "diagnostics.iosSDK") { config, source, date in guard let config = config as? [String: Any] else { return } let enabled = config["enabled"] as? Bool ?? false let sampleRate = config["sampleRate"] as? Double ?? 0.0 if let availabilities = config["availabilities"] as? [String: String], let crashTrackingVersion = availabilities["CrashTracking"] { print("Crash tracking available from version: \(crashTrackingVersion)") } print("Diagnostics enabled: \(enabled), sample rate: \(sampleRate)") } ``` -------------------------------- ### Version Comparison Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/MANIFEST.txt Shows how to compare SDK versions. This is useful for checking compatibility or feature availability. ```swift let currentVersion = amplitude.version let isCompatible = amplitude.utilities.isVersionCompatible(currentVersion, "1.4.0") ``` -------------------------------- ### ServerZone String Representation Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/types.md Demonstrates how to access the raw string value of ServerZone cases and initialize a ServerZone from a raw string value. ```swift ServerZone.US.rawValue // "US" ServerZone.EU.rawValue // "EU" ServerZone(rawValue: "US") // .US ServerZone(rawValue: "EU") // .EU ``` -------------------------------- ### AmplitudeContext Constructor Parameters Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/configuration.md Defines the parameters for initializing AmplitudeContext, including API key, instance name, server zone, and logger. ```swift public init(apiKey: String, instanceName: String = "$default_instance", serverZone: ServerZone = .US, logger: CoreLogger = OSLogger(logLevel: .error)) ``` -------------------------------- ### Configure Multiple SDK Instances Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/README.md Set up distinct Amplitude SDK instances for different purposes, such as main analytics and session replay, by providing unique instance names. Each instance maintains its own storage, configuration, and diagnostics. ```swift // Main analytics let mainContext = AmplitudeContext(apiKey: "key1", instanceName: "main") // Session replay let replayContext = AmplitudeContext(apiKey: "key2", instanceName: "replay") // Each maintains separate storage, config, and diagnostics ``` -------------------------------- ### Handle Session ID Changes Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/api-reference/plugin-system.md Implement `onSessionIdChanged` to be notified when a new session starts. The new session ID, represented as a Unix timestamp in milliseconds, is provided. ```swift func onSessionIdChanged(_ sessionId: Int64) ``` ```swift func onSessionIdChanged(_ sessionId: Int64) { let date = Date(timeIntervalSince1970: TimeInterval(sessionId) / 1000) print("New session started at: \(date)") } ``` -------------------------------- ### onStartProviding Method Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/api-reference/interface-signals.md Callback invoked when a provider begins emitting interface change notifications. This typically occurs when the first receiver is registered. ```swift func onStartProviding() ``` ```swift func onStartProviding() { print("Provider is now active") } ``` -------------------------------- ### Initialize RemoteConfigClient Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/api-reference/remote-config.md Creates a RemoteConfigClient instance. Requires an API key, server zone, and a logger. An optional instance name can be provided for caching. ```swift let logger = OSLogger(logLevel: .debug) let configClient = RemoteConfigClient( apiKey: "abc123xyz", serverZone: .US, instanceName: "main_app", logger: logger ) ``` -------------------------------- ### Initialize AmplitudeContext Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/README.md Initialize the AmplitudeContext with API credentials, server zone, and a logger. This object encapsulates SDK settings. ```swift let context = AmplitudeContext( apiKey: "your-api-key", instanceName: "my_app", serverZone: .US, logger: OSLogger(logLevel: .debug) ) ``` -------------------------------- ### Configure Multiple Amplitude Instances Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/configuration.md Set up multiple independent Amplitude instances for different purposes, such as main analytics and session replay. Each instance manages its own storage, remote configuration, and diagnostics. ```swift // Main analytics let mainContext = AmplitudeContext( apiKey: "key1", instanceName: "main_analytics" ) // Session replay let replayContext = AmplitudeContext( apiKey: "key2", instanceName: "session_replay", serverZone: .EU ) // Each instance maintains separate storage, remote config, and diagnostics ``` -------------------------------- ### Get Single Diagnostic Tag Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/api-reference/diagnostics.md Retrieves the value of a specific diagnostic tag by its name. Returns nil if the tag is not found. Useful for checking the current state of a tag. ```swift let version = await diagnosticsClient.getTag(name: "app_version") ``` -------------------------------- ### RemoteConfigClient Public Initializer Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/configuration.md Use this initializer to create a RemoteConfigClient instance. It requires an API key, server zone, and a logger. An optional instance name can be provided for storage isolation. ```swift public init(apiKey: String, serverZone: ServerZone, instanceName: String? = nil, logger: CoreLogger) ``` -------------------------------- ### Custom SessionReplayPlugin Receiver Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/api-reference/interface-signals.md An example implementation of an InterfaceSignalReceiver that acts as a plugin to manage session recording based on app lifecycle events. It prints status messages and controls recording state. ```swift class SessionReplayPlugin: UniversalPlugin, InterfaceSignalReceiver { var name: String? { "SessionReplay" } private var isRecording = false func onInterfaceChanged(signal: InterfaceChangeSignal) { if UIApplication.shared.applicationState == .active { print("App foregrounded at: \(signal.time)") startRecording() } else { print("App backgrounded at: \(signal.time)") pauseRecording() } } func onStartProviding() { print("Interface provider activated") } func onStopProviding() { print("Interface provider deactivated") } private func startRecording() { isRecording = true } private func pauseRecording() { isRecording = false } } ``` -------------------------------- ### Accessing Static Properties Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/api-reference/amplitude-context.md Demonstrates how to access the static properties `coreLibraryName` and `coreLibraryVersion` to retrieve information about the AmplitudeCore SDK. ```swift print(AmplitudeContext.coreLibraryName) print(AmplitudeContext.coreLibraryVersion) ``` -------------------------------- ### Custom Logger Implementation Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/MANIFEST.txt Shows how to implement a custom logger conforming to the SDK's logging interface. This allows for custom logging behavior or integration with existing logging frameworks. ```swift class MyLogger: AmplitudeLogger { func log(_ message: String, level: LogLevel) { print("[\(level)] \(message)") } } let logger = MyLogger() let amplitude = AmplitudeContext(configuration: configuration, logger: logger) ``` -------------------------------- ### Access Singleton Device Instance Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/api-reference/device.md Retrieve the singleton device instance to access platform-specific information. The correct implementation is automatically selected based on the current platform. ```swift let device = CoreDevice.current print("Device: \(device.manufacturer) \(device.model)") print("OS: \(device.os_name) \(device.os_version)") print("Platform: \(device.platform)") if let vendorId = device.identifierForVendor { print("Vendor ID: \(vendorId)") } ``` -------------------------------- ### Full AmplitudeContext Configuration Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/configuration.md Configure all parameters of AmplitudeContext, including a custom logger, instance name, and server zone, for detailed control. ```swift // Full configuration let customLogger = OSLogger(logLevel: .debug) let context = AmplitudeContext( apiKey: "abc123xyz", instanceName: "my_analytics", serverZone: .EU, logger: customLogger ) ``` -------------------------------- ### Implement a Custom Plugin Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/README.md Create a custom plugin by conforming to the UniversalPlugin protocol. Implement the execute method to modify events before upload and onIdentityChanged to react to user identification changes. ```swift class MyPlugin: UniversalPlugin { func execute(_ event: inout Event) { // Modify event before upload event.eventProperties?["custom_field"] = "value" } func onIdentityChanged(_ identity: AnalyticsIdentity) { // React to user identification } } ``` -------------------------------- ### Retrieve Plugins by Type Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/api-reference/plugin-system.md This method allows you to fetch all plugins that conform to a specified type. It's useful for batch operations or finding all instances of a certain kind of plugin. ```swift func plugins(type: PluginType.Type) -> [PluginType] ``` ```swift let replayPlugins = pluginHost.plugins(type: SessionReplayPlugin.self) for plugin in replayPlugins { print("Found session replay plugin: \(plugin.name ?? \"unnamed\")") } ``` -------------------------------- ### Handle Configuration Versioning Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/integration-guide.md Defines a `RemoteConfig` struct for decoding configuration and includes logic to check SDK version compatibility before applying the configuration. ```swift struct RemoteConfig: Decodable { let version: String let features: [String: Bool] let sampling: Double } func updateConfig(_ config: RemoteConfigClient.RemoteConfig?) { guard let config = config as? [String: Any] else { return } // Check version compatibility if let version = config["version"] as? String { do { let sdkVersion = "1.4.7" let compatible = try sdkVersion.isGreaterThanOrEqualToVersion(version) if !compatible { context?.logger.warn(message: "Config requires SDK version \(version)") return } } catch { context?.logger.error(message: "Failed to check version: \(error)") } } // Apply configuration applyConfig(config) } ``` -------------------------------- ### onStartProviding() Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/api-reference/interface-signals.md Called when the provider begins emitting notifications, typically after the first receiver has registered. This method signals that the provider is now active. ```APIDOC ## onStartProviding() ### Description Called when the provider starts emitting notifications (e.g., after first receiver registered). ### Usage ```swift func onStartProviding() { print("Provider is now active") } ``` ``` -------------------------------- ### AmplitudeContext Public Initializer Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/api-reference/amplitude-context.md Initializes an AmplitudeContext with public configuration. Remote config and diagnostics clients are created automatically. This is the primary way to configure the AmplitudeCore SDK. ```APIDOC ## Public Initializer ### Description Creates an `AmplitudeContext` with public configuration. Remote config and diagnostics clients are created automatically. ### Signature ```swift public init(apiKey: String, instanceName: String = "$default_instance", serverZone: ServerZone = .US, logger: CoreLogger = OSLogger(logLevel: .error)) ``` ### Parameters #### Parameters - **apiKey** (String) - Required. Amplitude project API key - **instanceName** (String) - Optional. Defaults to `"$default_instance"`. Identifier for this SDK instance - **serverZone** (ServerZone) - Optional. Defaults to `.US`. Data center region (`.US` or `.EU`) - **logger** (CoreLogger) - Optional. Defaults to `OSLogger(logLevel: .error)`. Logger for diagnostics output ### Returns `AmplitudeContext` ### Usage Examples #### Basic Initialization ```swift import AmplitudeCore let context = AmplitudeContext(apiKey: "your-api-key") ``` #### With Custom Configuration ```swift let context = AmplitudeContext( apiKey: "your-api-key", instanceName: "analytics", serverZone: .EU, logger: OSLogger(logLevel: .debug) ) ``` ``` -------------------------------- ### DiagnosticsClient Initializer Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/api-reference/diagnostics.md Initializes a new DiagnosticsClient instance. Configure parameters like API key, server zone, instance name, logging, sampling rate, and crash capture. ```swift public init(apiKey: String, serverZone: ServerZone = .US, instanceName: String, logger: CoreLogger = OSLogger(logLevel: .error), enabled: Bool = true, sampleRate: Double = DEFAULT_SAMPLE_RATE, crashCaptureEnabled: Bool = false, remoteConfigClient: RemoteConfigClient?, flushIntervalNanoSec: UInt64 = DEFAULT_FLUSH_INTERVAL * NSEC_PER_SEC, urlSessionConfiguration: URLSessionConfiguration = .ephemeral) ``` -------------------------------- ### Handle VersionError in Swift Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/errors.md Demonstrates how to use a do-catch block to handle specific VersionError cases like emptyVersionString and invalidVersionString, as well as a general catch-all for unexpected errors. ```swift do { let isGreater = try "1.4.7".isGreaterThanOrEqualToVersion("1.4.0") } catch VersionError.emptyVersionString { print("Empty version string provided") } catch VersionError.invalidVersionString(let version) { print("Invalid version format: \(version)") } catch { print("Unexpected error: \(error)") } ``` -------------------------------- ### Handling RemoteConfig Errors with Subscribe Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/errors.md Demonstrates how to subscribe to remote configuration updates and handle potential errors, such as unavailability, using the `waitForRemote` delivery mode. ```swift let configClient = RemoteConfigClient(apiKey: "key", serverZone: .US, logger: logger) configClient.subscribe(key: "myConfig", deliveryMode: .waitForRemote(timeout: 5)) { config, source, date in if let config = config { print("Got config from \(source)") } else { print("Config unavailable; check logs for RemoteConfigError") } } ``` -------------------------------- ### Subscribe to All Config Updates Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/api-reference/remote-config.md Subscribes to all configuration updates. The callback is invoked with the configuration, its source, and the fetch date. A subscription token is returned for later unsubscription. ```swift // Subscribe to all config let token = configClient.subscribe { config, source, date in print("Config updated from \(source)") if let config = config { print("Config keys: \(config.keys.joined(separator: ", "))") } } ``` -------------------------------- ### RemoteConfigClient Fetched Configuration Keys Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/configuration.md The client automatically requests these configuration keys from the server upon initialization. These keys are essential for various features like session replay and diagnostics. ```swift static let fetchedKeys = [ "sessionReplay.sr_ios_privacy_config", "sessionReplay.sr_ios_sampling_config", "analyticsSDK.iosSDK", "diagnostics.iosSDK", ] ``` -------------------------------- ### Reacting to Identity and Session Changes (Swift) Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/integration-guide.md Implement callbacks to respond to user identity changes, session ID updates, opt-out status, and user resets. These methods allow for dynamic adjustments to tracking and internal state. ```swift func onIdentityChanged(_ identity: AnalyticsIdentity) { if let userId = identity.userId { context?.logger.debug(message: "User identified: \(userId)") } // Update internal state updateUserContext(identity) } func onSessionIdChanged(_ sessionId: Int64) { let date = Date(timeIntervalSince1970: TimeInterval(sessionId) / 1000) context?.logger.debug(message: "New session at \(date)") // Reset session-specific state sessionState.reset() } func onOptOutChanged(_ optOut: Bool) { context?.logger.debug(message: "Opt-out: \(optOut)") if optOut { // Stop tracking pauseTracking() } else { // Resume tracking resumeTracking() } } func onReset() { context?.logger.debug(message: "User reset") // Clear user-specific data clearUserData() } ``` -------------------------------- ### Sample Session Data Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/api-reference/utilities.md Use `Sample.isInSample` to determine if a session should be sampled based on a provided seed and sample rate. This is useful for controlling the volume of data sent to Amplitude. ```swift // Determine if session should be sampled at 25% let sessionStart = String(Date().timeIntervalSince1970) let shouldSample = Sample.isInSample(seed: sessionStart, sampleRate: 0.25) if shouldSample { print("Session sampled for detailed tracking") } ``` -------------------------------- ### Build HTTP POST Request Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/api-reference/utilities.md Construct an HTTP POST request using `HttpUtil.makeJsonRequest`. This utility helps in setting up the request URL, method, body, and API key header for sending data to the Amplitude API. ```swift let endpoint = URL(string: "https://api.amplitude.com/2/httpapi")! var request = HttpUtil.makeJsonRequest(url: endpoint) request.httpMethod = "POST" request.httpBody = eventData request.setValue(apiKey, forHTTPHeaderField: "X-ApiKey") ``` -------------------------------- ### DiagnosticsClient Initializer Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/api-reference/diagnostics.md Initializes a new instance of the DiagnosticsClient. This client is responsible for collecting and transmitting diagnostic information. ```APIDOC ## Initializer ### Description Creates a diagnostics client. ### Signature ```swift public init(apiKey: String, serverZone: ServerZone = .US, instanceName: String, logger: CoreLogger = OSLogger(logLevel: .error), enabled: Bool = true, sampleRate: Double = DEFAULT_SAMPLE_RATE, crashCaptureEnabled: Bool = false, remoteConfigClient: RemoteConfigClient? = nil, flushIntervalNanoSec: UInt64 = DEFAULT_FLUSH_INTERVAL * NSEC_PER_SEC, urlSessionConfiguration: URLSessionConfiguration = .ephemeral) ``` ### Parameters #### Path Parameters * None #### Query Parameters * None #### Request Body * None ### Parameters - **apiKey** (`String`) - Required - Amplitude API key - **serverZone** (`ServerZone`) - Optional - Server region, defaults to `.US` - **instanceName** (`String`) - Required - SDK instance identifier for storage isolation - **logger** (`CoreLogger`) - Optional - Logger for diagnostics, defaults to `OSLogger(logLevel: .error)` - **enabled** (`Bool`) - Optional - Enable/disable diagnostics capture, defaults to `true` - **sampleRate** (`Double`) - Optional - Fraction of sessions to sample [0.0-1.0], defaults to `DEFAULT_SAMPLE_RATE` - **crashCaptureEnabled** (`Bool`) - Optional - Unused; retained for compatibility, defaults to `false` - **remoteConfigClient** (`RemoteConfigClient?`) - Optional - Client for fetching remote config, defaults to `nil` - **flushIntervalNanoSec** (`UInt64`) - Optional - Seconds between auto-flushes, defaults to `DEFAULT_FLUSH_INTERVAL * NSEC_PER_SEC` - **urlSessionConfiguration** (`URLSessionConfiguration`) - Optional - Session configuration for uploads, defaults to `.ephemeral` ### Returns `DiagnosticsClient` ``` -------------------------------- ### Enable Verbose Logging Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/errors.md Initialize an OSLogger with debug log level and provide it to the AmplitudeContext for verbose logging. ```swift let logger = OSLogger(logLevel: .debug) let context = AmplitudeContext( apiKey: "key", logger: logger ) ``` -------------------------------- ### CoreDevice Singleton Access Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/api-reference/device.md Access the singleton `CoreDevice` instance to retrieve device information. The `current` property automatically detects and returns the appropriate platform-specific implementation. ```APIDOC ## CoreDevice Singleton Access ### Description Access the singleton `CoreDevice` instance to retrieve device information. The `current` property automatically detects and returns the appropriate platform-specific implementation. ### Method `static let current: CoreDevice` ### Returns - `CoreDevice`: The singleton device instance, which is a platform-specific implementation (e.g., `IOSDevice`, `MacOSDevice`, `WatchOSDevice`) or a generic `CoreDevice` for unsupported platforms. ### Usage Example ```swift let device = CoreDevice.current print("Device: \(device.manufacturer) \(device.model)") print("OS: \(device.os_name) \(device.os_version)") print("Platform: \(device.platform)") if let vendorId = device.identifierForVendor { print("Vendor ID: \(vendorId)") } ``` ``` -------------------------------- ### Batch Remote Config Subscription in Swift Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/integration-guide.md Subscribe to multiple remote configurations at once instead of individual subscriptions. This reduces overhead by receiving all relevant configurations in a single callback. ```swift func subscribeToMultipleConfigs() { // Instead of multiple subscriptions, subscribe once context.remoteConfigClient.subscribe( key: "mySDK", callback: { config, source, date in // Receive all configs under "mySDK" at once // mySDK.iosSDK.sampling // mySDK.iosSDK.features // etc. } ) } ``` -------------------------------- ### Subscribe to Remote Config with Key Path Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/api-reference/remote-config.md Subscribe to configuration updates using a dot-delimited key path to navigate nested JSON structures. The callback receives the configuration object, its source, and the update date. ```swift // Config structure: // { // "sessionReplay": { // "sr_ios_sampling_config": { // "sampleRate": 0.1, // "enabled": true // } // } // } configClient.subscribe(key: "sessionReplay.sr_ios_sampling_config") { config, source, date in // config is {"sampleRate": 0.1, "enabled": true} } ``` -------------------------------- ### LogLevel Comparison Semantics Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/types.md Illustrates the comparison semantics of the LogLevel enum, showing how different levels relate to each other. ```swift LogLevel.error < LogLevel.warn // true LogLevel.debug >= LogLevel.log // true ``` -------------------------------- ### Remote Configuration Subscription Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/MANIFEST.txt Shows how to subscribe to remote configuration updates. This allows the application to dynamically fetch and apply configuration changes. ```swift amplitude.remoteConfiguration.subscribe { config in print("Remote config updated: \(config)") } ``` -------------------------------- ### flush() Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/api-reference/diagnostics.md Sends all accumulated diagnostics to Amplitude servers and clears buffers. ```APIDOC ## flush() ### Description Sends all accumulated diagnostics to Amplitude servers and clears buffers. ### Method Signature ```swift func flush() async ``` ### Usage Example ```swift await diagnosticsClient.flush() ``` ``` -------------------------------- ### HTTP Request Building Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/MANIFEST.txt Demonstrates the construction of an HTTP request for sending data to Amplitude. This is an internal utility and typically not modified. ```swift let request = amplitude.utilities.buildHTTPRequest(path: "/2/events/identify", body: data) ``` -------------------------------- ### Mock Analytics Client for Swift Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/integration-guide.md Implement a mock analytics client to isolate and test plugin behavior without sending real events. This mock captures tracked events for verification. ```swift class MockAnalyticsClient: AnalyticsClient { typealias Identity = MockIdentity var identity: MockIdentity { MockIdentity() } var sessionId: Int64 { 0 } var optOut: Bool { false } var trackedEvents: [(String, [String: Any]?)] = [] func track(eventType: String, eventProperties: [String: Any]?) { trackedEvents.append((eventType, eventProperties)) } } struct MockIdentity: AnalyticsIdentity { var deviceId: String? { nil } var userId: String? { nil } var userProperties: [String: Any] { [:] } } // Usage in tests let mockClient = MockAnalyticsClient() let plugin = MyPlugin() plugin.setup(analyticsClient: mockClient, amplitudeContext: testContext) // Verify plugin behavior XCTAssertEqual(mockClient.trackedEvents.count, expectedCount) ``` -------------------------------- ### Create Separate Amplitude Instances Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/integration-guide.md Instantiate multiple AmplitudeContext objects for distinct purposes like analytics, session replay, and crash handling. Each instance maintains isolated configurations, storage, and logging. ```swift // Main analytics with sampling let analyticsContext = AmplitudeContext( apiKey: "analytics-key", instanceName: "analytics", serverZone: .US, logger: OSLogger(logLevel: .error) ) // Session replay with different sampling let replayContext = AmplitudeContext( apiKey: "replay-key", instanceName: "session_replay", serverZone: .EU, logger: OSLogger(logLevel: .error) ) // Crash handling let crashContext = AmplitudeContext( apiKey: "crash-key", instanceName: "crashes", serverZone: .US ) // Each has isolated: // - Remote config cache // - Diagnostics storage // - Logger // - API key ``` -------------------------------- ### Register and Detect Application Crashes Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/api-reference/utilities.md Utilize `CrashCatcher.register` on application startup to enable crash detection. Check `CrashCatcher.didLastRunCrash` and use `CrashCatcher.consumePreviousCrash` to retrieve and send crash reports. ```swift // On app startup CrashCatcher.register() // Check for previous crash let didCrash = CrashCatcher.didLastRunCrash if didCrash, let report = CrashCatcher.consumePreviousCrash() { // Send crash report to analytics analyticsClient.track(eventType: "app_crash", eventProperties: [ "crash_report": report ]) } ``` -------------------------------- ### Add and Use Plugins Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/integration-guide.md Add custom plugins to your AnalyticsClient and track events. Plugins intercept and enrich events before they are processed and uploaded. ```swift let analyticsClient = MyAnalyticsClient(context: context) // Add a plugin let myPlugin = MyEnrichmentPlugin() myPlugin.setup(analyticsClient: analyticsClient, amplitudeContext: context) // Track an event analyticsClient.track(eventType: "page_view", eventProperties: [ "page_name": "home" ]) // Plugin intercepts and enriches event before upload ``` -------------------------------- ### Deterministic Sampling with Sample Class Source: https://github.com/amplitude/amplitudecore-swift/blob/main/_autodocs/api-reference/utilities.md Use the Sample class for deterministic sampling based on a seed and sample rate. It ensures consistent results for the same inputs. ```swift public class Sample ```