### Install Amplitude Swift SDK Source: https://context7.com/amplitude/amplitude-swift/llms.txt Instructions for installing the Amplitude Swift SDK using Swift Package Manager, CocoaPods, and Carthage. ```swift // Package.swift dependencies: [ .package(url: "https://github.com/amplitude/Amplitude-Swift.git", from: "1.17.3") ] ``` ```ruby # Podfile pod 'AmplitudeSwift', '~> 1.17.3' ``` ```bash # Cartfile github "amplitude/Amplitude-Swift" ~> 1.17.3 ``` -------------------------------- ### Manage User Identification in Amplitude Swift SDK Source: https://context7.com/amplitude/amplitude-swift/llms.txt Guides on setting and retrieving user IDs, device IDs, and session IDs. Includes resetting user identity and direct manipulation of the identity object. ```swift // Set user ID when user logs in amplitude.setUserId(userId: "user@example.com") // Set custom device ID amplitude.setDeviceId(deviceId: "custom-device-id-123") // Get current identifiers let userId = amplitude.getUserId() // Returns: "user@example.com" let deviceId = amplitude.getDeviceId() // Returns: "custom-device-id-123" let sessionId = amplitude.getSessionId() // Returns current session timestamp // Reset user on logout (generates new device ID) amplitude.reset() // Access and modify identity directly var identity = amplitude.identity identity.userId = "new-user-id" amplitude.identity = identity ``` -------------------------------- ### Track Events in Amplitude Swift SDK Source: https://context7.com/amplitude/amplitude-swift/llms.txt Examples of tracking custom events with and without properties, using BaseEvent for more control, and handling callbacks for event confirmation. ```swift // Simple event tracking amplitude.track(eventType: "Button Clicked") // Event with properties amplitude.track( eventType: "Product Viewed", eventProperties: [ "product_id": "SKU-12345", "product_name": "Premium Widget", "category": "Electronics", "price": 99.99, "currency": "USD" ] ) // Using BaseEvent for more control let event = BaseEvent( eventType: "Purchase Completed", eventProperties: [ "order_id": "ORD-789", "total_amount": 149.99, "items_count": 3 ] ) amplitude.track(event: event) // Event with callback for confirmation amplitude.track( event: BaseEvent(eventType: "Critical Action"), callback: { event, code, message in if code == 200 { print("Event \(event.eventType) successfully sent") } else { print("Failed to send event: \(message)") } } ) // Event with custom options let options = EventOptions( userId: "user-456", deviceId: "device-789", timestamp: Int64(Date().timeIntervalSince1970 * 1000) ) amplitude.track(eventType: "Custom Event", eventProperties: nil, options: options) ``` -------------------------------- ### Session Management with Swift Source: https://context7.com/amplitude/amplitude-swift/llms.txt Control session tracking with automatic session detection or manual session ID management for custom session logic. This includes getting the current session ID, starting a new session with a timestamp or Date object, ending the current session, and configuring session timeout in the configuration. ```swift let sessionId = amplitude.getSessionId() print("Current session: \(sessionId)") let timestamp = Int64(Date().timeIntervalSince1970 * 1000) amplitude.setSessionId(timestamp: timestamp) amplitude.setSessionId(date: Date()) amplitude.setSessionId(timestamp: -1) let config = Configuration( apiKey: "YOUR_API_KEY", minTimeBetweenSessionsMillis: 1800000 // 30 minutes ) let amplitude = Amplitude(configuration: config) ``` -------------------------------- ### Initialize Amplitude Swift SDK Source: https://context7.com/amplitude/amplitude-swift/llms.txt Demonstrates how to initialize the Amplitude SDK with basic and full configuration options, including API key, flush settings, logging, and tracking options. ```swift import AmplitudeSwift // Basic initialization with minimum configuration let amplitude = Amplitude( configuration: Configuration(apiKey: "YOUR_API_KEY") ) // Full configuration with all options let amplitude = Amplitude( configuration: Configuration( apiKey: "YOUR_API_KEY", flushQueueSize: 30, flushIntervalMillis: 30000, instanceName: "my-app", optOut: false, logLevel: LogLevelEnum.debug, minIdLength: 5, partnerId: "partner-123", callback: { (event: BaseEvent, code: Int, message: String) in print("Event sent: \(event.eventType), code: \(code), message: \(message)") }, flushMaxRetries: 5, useBatch: false, serverZone: .US, trackingOptions: TrackingOptions() .disableTrackCarrier() .disableTrackDMA(), enableCoppaControl: false, flushEventsOnClose: true, minTimeBetweenSessionsMillis: 300000, autocapture: [.sessions, .appLifecycles, .screenViews], identifyBatchIntervalMillis: 30000, migrateLegacyData: true ) ) ``` -------------------------------- ### Amplitude SDK Usage in Objective-C Source: https://context7.com/amplitude/amplitude-swift/llms.txt Demonstrates how to initialize, track events, set user properties, track revenue, and flush events using the Amplitude SDK with Objective-C wrapper classes. ```objectivec // Import the SDK @import AmplitudeSwift; // Initialize Amplitude AMPConfiguration *config = [[AMPConfiguration alloc] initWithApiKey:@"YOUR_API_KEY"]; config.logLevel = AMPLogLevelDebug; config.flushEventsOnClose = YES; Amplitude *amplitude = [[Amplitude alloc] initWithConfiguration:config]; // Track events [amplitude track:@"Button Clicked" eventProperties:@{ @"button_name": @"Submit", @"screen": @"Checkout" }]; // Set user properties AMPIdentify *identify = [[AMPIdentify alloc] init]; [identify set:@"plan" value:@"premium"]; [identify set:@"age" value:@28]; [amplitude identify:identify]; // Set user ID [amplitude setUserId:@"user@example.com"]; // Track revenue AMPRevenue *revenue = [[AMPRevenue alloc] init]; revenue.productId = @"premium_sub"; revenue.price = 9.99; revenue.quantity = 1; [amplitude revenue:revenue]; // Flush events [amplitude flush]; ``` -------------------------------- ### Configure Server Zone for Data Residency Source: https://context7.com/amplitude/amplitude-swift/llms.txt Set the server zone for data residency, supporting US (default), EU for GDPR compliance, or custom server URLs for proxy configurations. ```swift // US data residency (default) let usConfig = Configuration( apiKey: "YOUR_API_KEY", serverZone: .US ) // EU data residency for GDPR compliance let euConfig = Configuration( apiKey: "YOUR_API_KEY", serverZone: .EU ) // Custom server URL (e.g., for proxy) let customConfig = Configuration( apiKey: "YOUR_API_KEY", serverUrl: "https://your-proxy.example.com/amplitude" ) ``` -------------------------------- ### Configure Autocapture Options in Swift Source: https://context7.com/amplitude/amplitude-swift/llms.txt Configure automatic event capture for sessions, lifecycle events, screen views, user interactions, network requests, and frustration signals. This involves initializing the SDK with specific autocapture settings. ```swift // Enable all autocapture options let configAll = Configuration( apiKey: "YOUR_API_KEY", autocapture: .all ) // Enable specific autocapture options let configCustom = Configuration( apiKey: "YOUR_API_KEY", autocapture: [ .sessions, // Session start/end events .appLifecycles, // App install, update, open, background events .screenViews, // Automatic screen view tracking .elementInteractions // Button taps and UI interactions ] ) // Enable network tracking and frustration detection let configAdvanced = Configuration( apiKey: "YOUR_API_KEY", autocapture: [ .sessions, .appLifecycles, .networkTracking, // HTTP request/response tracking .frustrationInteractions // Rage clicks and dead clicks ] ) // Sessions only (default) let configDefault = Configuration( apiKey: "YOUR_API_KEY", autocapture: .sessions ) // Disable all autocapture let configNone = Configuration( apiKey: "YOUR_API_KEY", autocapture: [] ) ``` -------------------------------- ### Identify User Properties with Swift Source: https://context7.com/amplitude/amplitude-swift/llms.txt Use the Identify class to set, update, and manage user properties with various operations like set, setOnce, add, append, prepend, and more. This includes basic property setting, conditional setting, numeric increments, array manipulations, unsetting, clearing properties, and a shorthand using a dictionary. ```swift let identify = Identify() .set(property: "plan", value: "premium") .set(property: "age", value: 28) .set(property: "interests", value: ["music", "sports", "tech"]) amplitude.identify(identify: identify) let identifyOnce = Identify() .setOnce(property: "initial_referrer", value: "google") .setOnce(property: "first_login_date", value: "2024-01-15") amplitude.identify(identify: identifyOnce) let identifyAdd = Identify() .add(property: "login_count", value: 1) .add(property: "total_purchases", value: 5) amplitude.identify(identify: identifyAdd) let identifyArray = Identify() .append(property: "viewed_products", value: "product-123") .prepend(property: "recent_searches", value: "swift sdk") .preInsert(property: "unique_categories", value: "electronics") .postInsert(property: "wish_list", value: "item-456") .remove(property: "cart_items", value: "removed-item") amplitude.identify(identify: identifyArray) let identifyUnset = Identify() .unset(property: "temporary_flag") amplitude.identify(identify: identifyUnset) let identifyClear = Identify().clearAll() amplitude.identify(identify: identifyClear) amplitude.identify(userProperties: [ "name": "John Doe", "email": "john@example.com", "premium": true ]) ``` -------------------------------- ### Track Revenue with Swift Source: https://context7.com/amplitude/amplitude-swift/llms.txt Track revenue events with product details, price, quantity, and optional receipt validation for in-app purchases. This includes basic revenue tracking, revenue with additional properties, revenue with receipt validation (iOS), and a direct revenue event. ```swift let revenue = Revenue() revenue.productId = "premium_subscription" revenue.price = 9.99 revenue.quantity = 1 revenue.revenueType = "subscription" revenue.currency = "USD" amplitude.revenue(revenue: revenue) let purchaseRevenue = Revenue() purchaseRevenue.productId = "item-sku-123" purchaseRevenue.price = 29.99 purchaseRevenue.quantity = 2 purchaseRevenue.revenueType = "purchase" purchaseRevenue.currency = "EUR" purchaseRevenue.properties = [ "discount_applied": true, "promo_code": "SAVE20", "category": "accessories" ] amplitude.revenue(revenue: purchaseRevenue) let validatedRevenue = Revenue() validatedRevenue.productId = "premium_yearly" validatedRevenue.price = 99.99 validatedRevenue.quantity = 1 validatedRevenue.setReceipt( receipt: "base64-encoded-receipt-data", receiptSignature: "receipt-signature" ) amplitude.revenue(revenue: validatedRevenue) let revenueEvent = RevenueEvent() revenueEvent.eventProperties = [ "$productId": "product-456", "$price": 14.99, "$quantity": 1, "$revenueType": "refund", "$revenue": -14.99 ] amplitude.revenue(event: revenueEvent) ``` -------------------------------- ### Extend Amplitude SDK with Plugins in Swift Source: https://context7.com/amplitude/amplitude-swift/llms.txt Extend SDK functionality using the plugin system with different plugin types for preprocessing, enrichment, and custom destinations. Plugins can modify events, filter them, or observe their tracking. ```swift // Custom enrichment plugin to add properties to all events class EnrichmentPlugin: EnrichmentPlugin { override func execute(event: BaseEvent) -> BaseEvent? { // Add custom properties to every event var properties = event.eventProperties ?? [:] properties["app_build"] = Bundle.main.infoDictionary?["CFBundleVersion"] properties["environment"] = "production" properties["custom_timestamp"] = ISO8601DateFormatter().string(from: Date()) event.eventProperties = properties return event } } // Add plugin to amplitude amplitude.add(plugin: EnrichmentPlugin()) // Filter plugin to block certain events class FilterPlugin: EnrichmentPlugin { private let blockedEventTypes = ["debug_event", "test_event"] override func execute(event: BaseEvent) -> BaseEvent? { if blockedEventTypes.contains(event.eventType) { return nil // Block the event } return event } } amplitude.add(plugin: FilterPlugin()) // Observer plugin to log all events class LoggingPlugin: ObservePlugin { override func execute(event: BaseEvent) -> BaseEvent? { print("Event tracked: \(event.eventType)") if let props = event.eventProperties { print("Properties: \(props)") } return event } } amplitude.add(plugin: LoggingPlugin()) // Remove a plugin amplitude.remove(plugin: myPlugin) // Apply closure to all plugins amplitude.apply { plugin in print("Plugin type: \(plugin.type)") } ``` -------------------------------- ### Configure Event Flushing and Batch Mode Source: https://context7.com/amplitude/amplitude-swift/llms.txt Manually trigger event uploads or configure automatic flushing behavior. Supports batch mode for high-volume applications by setting queue sizes and intervals. ```swift // Manually flush all queued events amplitude.flush() // Configure flush behavior in configuration let config = Configuration( apiKey: "YOUR_API_KEY", flushQueueSize: 30, // Flush when 30 events queued flushIntervalMillis: 30000, // Flush every 30 seconds flushEventsOnClose: true, // Flush when app backgrounds flushMaxRetries: 5 // Retry failed uploads 5 times ) // Batch mode for high-volume applications let batchConfig = Configuration( apiKey: "YOUR_API_KEY", useBatch: true, flushQueueSize: 50, flushIntervalMillis: 60000 ) ``` -------------------------------- ### Control Data Collection with Tracking Options in Swift Source: https://context7.com/amplitude/amplitude-swift/llms.txt Control what device and location data the SDK collects using TrackingOptions to comply with privacy requirements. This includes disabling specific data points or enabling COPPA compliance. ```swift // Disable specific tracking options let trackingOptions = TrackingOptions() .disableTrackCarrier() // Don't track carrier info .disableTrackCity() // Don't track city .disableTrackCountry() // Don't track country .disableTrackDMA() // Don't track DMA .disableTrackIDFV() // Don't track IDFV .disableTrackIpAddress() // Don't track IP address .disableTrackLanguage() // Don't track language .disableTrackOsName() // Don't track OS name .disableTrackOsVersion() // Don't track OS version .disableTrackPlatform() // Don't track platform .disableTrackRegion() // Don't track region .disableTrackDeviceModel() // Don't track device model .disableTrackDeviceManufacturer() // Don't track manufacturer .disableTrackVersionName() // Don't track app version let config = Configuration( apiKey: "YOUR_API_KEY", trackingOptions: trackingOptions ) let amplitude = Amplitude(configuration: config) // Enable COPPA compliance (disables IDFA, IDFV, city, IP) let coppaConfig = Configuration( apiKey: "YOUR_API_KEY", enableCoppaControl: true ) let coppaAmplitude = Amplitude(configuration: coppaConfig) ``` -------------------------------- ### Group Analytics with Swift Source: https://context7.com/amplitude/amplitude-swift/llms.txt Associate users with groups and set group-level properties for B2B analytics and organizational tracking. This includes setting a user to a single group, multiple groups of the same type, setting group properties using groupIdentify, and a shorthand for group properties. ```swift amplitude.setGroup(groupType: "company", groupName: "Amplitude Inc") amplitude.setGroup(groupType: "team", groupName: ["Engineering", "Mobile", "Analytics"]) let groupIdentify = Identify() .set(property: "industry", value: "Technology") .set(property: "employee_count", value: 500) .set(property: "plan", value: "enterprise") .set(property: "region", value: "North America") amplitude.groupIdentify( groupType: "company", groupName: "Amplitude Inc", identify: groupIdentify ) amplitude.groupIdentify( groupType: "company", groupName: "Acme Corp", groupProperties: [ "founded_year": 2010, "public": true, "headquarters": "San Francisco" ] ) ``` -------------------------------- ### Manage User Opt-Out for Event Tracking Source: https://context7.com/amplitude/amplitude-swift/llms.txt Enable or disable event tracking for users to comply with privacy preferences. This can be configured at initialization or toggled at runtime. ```swift // Opt out of tracking (no events will be sent) amplitude.configuration.optOut = true // Check opt-out status let isOptedOut = amplitude.configuration.optOut // Re-enable tracking amplitude.configuration.optOut = false // Configure opt-out at initialization let config = Configuration( apiKey: "YOUR_API_KEY", optOut: UserDefaults.standard.bool(forKey: "analytics_opt_out") ) ``` -------------------------------- ### Configure and Manage Offline Event Mode Source: https://context7.com/amplitude/amplitude-swift/llms.txt Enable offline mode to queue events when network connectivity is unavailable and automatically upload them when the connection is restored. Supports runtime toggling and disabling network checks. ```swift // Start in offline mode let offlineConfig = Configuration( apiKey: "YOUR_API_KEY", offline: true ) var amplitude = Amplitude(configuration: offlineConfig) // Toggle offline mode at runtime amplitude.configuration.offline = true // Go offline amplitude.configuration.offline = false // Go online // Events are queued while offline and sent when back online amplitude.track(eventType: "Offline Event") // Queued amplitude.configuration.offline = false // Sends queued events // Disable network connectivity checking let noCheckConfig = Configuration( apiKey: "YOUR_API_KEY", offline: NetworkConnectivityCheckerPlugin.Disabled ) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.