### Objective-C Usage for RudderStack SDK Configuration Source: https://context7.com/rudderlabs/rudder-sdk-swift/llms.txt The SDK provides full Objective-C compatibility with builder patterns for configuration. This example demonstrates how to initialize and configure the RudderStack SDK in Objective-C. ```objective-c #import @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // Configure logging [RSSLoggerAnalytics setLogLevel:RSSLogLevelVerbose]; // Build configuration RSSConfigurationBuilder *builder = [[RSSConfigurationBuilder alloc] initWithWriteKey:@"YOUR_WRITE_KEY" dataPlaneUrl:@"https://your-data-plane.rudderlabs.com"]; [builder setGzipEnabled:YES]; [builder setCollectDeviceId:YES]; [builder setTrackApplicationLifecycleEvents:YES]; // Configure flush policies NSArray *flushPolicies = @[ [RSSStartupFlushPolicy new], [RSSFrequencyFlushPolicy new], [RSSCountFlushPolicy new] ]; [builder setFlushPolicies:flushPolicies]; // Configure session RSSSessionConfigurationBuilder *sessionBuilder = [RSSSessionConfigurationBuilder new]; [builder setSessionConfiguration:[sessionBuilder build]]; // Initialize analytics self.analytics = [[RSSAnalytics alloc] initWithConfiguration:[builder build]]; return YES; } // Track events - (void)trackPurchase { [self.analytics track:@"Purchase Completed" properties:@{@"revenue": @99.99, @"currency": @"USD"} options:nil]; } // Identify users - (void)identifyUser { [self.analytics identify:@"user_123" traits:@{@"name": @"John", @"email": @"john@example.com"} options:nil]; } // Reset with selective options - (void)logoutUser { RSSResetEntriesBuilder *entriesBuilder = [RSSResetEntriesBuilder new]; [entriesBuilder setAnonymousIdResetEntry:YES]; [entriesBuilder setUserIdResetEntry:YES]; [entriesBuilder setTraitsResetEntry:YES]; [entriesBuilder setSessionResetEntry:NO]; RSSResetOptionsBuilder *optionsBuilder = [RSSResetOptionsBuilder new]; [optionsBuilder setEntries:[entriesBuilder build]]; [self.analytics resetWithOptions:[optionsBuilder build]]; } @end ``` -------------------------------- ### Initialize RudderStack SDK with Multiple Integrations (Swift) Source: https://github.com/rudderlabs/rudder-sdk-swift/blob/main/README.md Demonstrates how to initialize the RudderStack SDK and add multiple third-party integrations like Adjust and Firebase. Ensure the necessary integration dependencies are added via Swift Package Manager before initialization. This example assumes you have a valid write key and data plane URL. ```swift import RudderStackAnalytics import RudderIntegrationAdjust import RudderIntegrationFirebase class AppDelegate: UIResponder, UIApplicationDelegate { var analytics: Analytics? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Initialize the RudderStack Analytics SDK let config = Configuration( writeKey: "", dataPlaneUrl: "" ) self.analytics = Analytics(configuration: config) // Add integrations analytics?.add(plugin: AdjustIntegration()) analytics?.add(plugin: FirebaseIntegration()) // Add more integrations as needed return true } } ``` -------------------------------- ### Develop Custom Plugins with Swift Source: https://context7.com/rudderlabs/rudder-sdk-swift/llms.txt Create custom plugins to modify events, add context data, or extend SDK functionality. Includes an example of adding device advertising ID to event context. ```swift import RudderStackAnalytics // Custom plugin to add device advertising ID final class AdvertisingIdPlugin: Plugin { var pluginType: PluginType = .onProcess var analytics: Analytics? func setup(analytics: Analytics) { self.analytics = analytics } func intercept(event: any Event) -> (any Event)? { var updatedEvent = event var contextDict = event.context?.rawDictionary ?? [: ] // Add advertising ID to context contextDict["device"] = [ "advertisingId": "sample-advertising-id", "adTrackingEnabled": true ] updatedEvent.context = contextDict.codableWrapped return updatedEvent } func teardown() { // Cleanup resources if needed } } // Add plugin to analytics analytics?.add(plugin: AdvertisingIdPlugin()) // Remove plugin when no longer needed let plugin = AdvertisingIdPlugin() analytics?.add(plugin: plugin) analytics?.remove(plugin: plugin) ``` -------------------------------- ### Manage Sessions Manually with Swift Source: https://context7.com/rudderlabs/rudder-sdk-swift/llms.txt Control user sessions programmatically with manual start and end capabilities. Supports starting sessions with auto-generated or custom IDs, retrieving the current session ID, and ending sessions. ```swift // Start a new session (auto-generates session ID) analytics?.startSession() // Start session with custom ID (must be at least 10 digits) analytics?.startSession(sessionId: 1234567890) // Get current session ID if let sessionId = analytics?.sessionId { print("Current session: \(sessionId)") } // End the current session analytics?.endSession() ``` -------------------------------- ### Install RudderStack Swift SDK using Swift Package Manager Source: https://context7.com/rudderlabs/rudder-sdk-swift/llms.txt This snippet shows how to add the RudderStack Swift SDK to your project's `Package.swift` file using Swift Package Manager. It specifies the package URL and version, and then links the SDK product to your application target. Ensure your project supports the specified platforms. ```swift // Package.swift // swift-tools-version:5.9 import PackageDescription let package = Package( name: "MyApp", platforms: [ .iOS(.v15), .macOS(.v12), .tvOS(.v15), .watchOS(.v8) ], dependencies: [ .package(url: "https://github.com/rudderlabs/rudder-sdk-swift.git", .upToNextMajor(from: "1.0.1")) ], targets: [ .target( name: "MyApp", dependencies: [ .product(name: "RudderStackAnalytics", package: "rudder-sdk-swift") ] ) ] ) ``` -------------------------------- ### Swift Integration Plugin for Device-Mode Destinations Source: https://context7.com/rudderlabs/rudder-sdk-swift/llms.txt Create integration plugins to send events directly to third-party SDKs without routing through RudderStack servers. This example shows how to implement a custom integration plugin for RudderStack Analytics in Swift. ```swift import RudderStackAnalytics class MyAnalyticsIntegration: IntegrationPlugin { var pluginType: PluginType = .terminal var analytics: Analytics? var key: String = "MyAnalytics" private var destinationSDK: MyDestinationSDK? func create(destinationConfig: [String: Any]) throws { // Initialize the third-party SDK destinationSDK = MyDestinationSDK(apiKey: "your-api-key") } func getDestinationInstance() -> Any? { return destinationSDK } func track(payload: TrackEvent) { destinationSDK?.logEvent( name: payload.event, properties: payload.properties?.dictionary?.rawDictionary ?? [:] ) } func identify(payload: IdentifyEvent) { destinationSDK?.setUser( userId: payload.userId ?? "", traits: analytics?.traits ?? [:] ) } func screen(payload: ScreenEvent) { destinationSDK?.trackScreen(name: payload.event) } func flush() { destinationSDK?.flush() } func reset() { destinationSDK?.reset() } } // Add integration and listen for ready state let integration = MyAnalyticsIntegration() analytics?.add(plugin: integration) integration.onDestinationReady { destination, result in switch result { case .success: print("Destination \(integration.key) is ready") case .failure(let error): print("Destination failed: \(error.localizedDescription)") } } ``` -------------------------------- ### Swift Custom Logger Implementation for RudderStack Source: https://context7.com/rudderlabs/rudder-sdk-swift/llms.txt Implement custom logging to integrate with your preferred logging framework. This example shows how to create a custom logger class that conforms to the RudderStack Logger protocol in Swift. ```swift import RudderStackAnalytics // Custom logger implementation class CustomLogger: Logger { func verbose(log: String) { // Send to your logging system MyLoggingService.log(level: .verbose, message: "[RudderStack] \(log)") } func debug(log: String) { MyLoggingService.log(level: .debug, message: "[RudderStack] \(log)") } func info(log: String) { MyLoggingService.log(level: .info, message: "[RudderStack] \(log)") } func warn(log: String) { MyLoggingService.log(level: .warning, message: "[RudderStack] \(log)") } func error(log: String, error: Error?) { let message = error != nil ? "\(log) - \(error!.localizedDescription)" : log MyLoggingService.log(level: .error, message: "[RudderStack] \(message)") } } // Configure logging LoggerAnalytics.logLevel = .debug // Options: .none, .error, .warn, .info, .debug, .verbose LoggerAnalytics.setLogger(CustomLogger()) ``` -------------------------------- ### Initialize RudderStack Analytics SDK (Swift) Source: https://github.com/rudderlabs/rudder-sdk-swift/blob/main/README.md This code initializes the RudderStack Analytics SDK in a Swift application. It requires a write key and a data plane URL obtained from the RudderStack dashboard. The initialization should be done at the application's entry point. ```swift import RudderStackAnalytics class AppDelegate: UIResponder, UIApplicationDelegate { var analytics: Analytics? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Initialize the RudderStack Analytics SDK let config = Configuration( writeKey: "", dataPlaneUrl: "" ) self.analytics = Analytics(configuration: config) return true } } ``` -------------------------------- ### Track User Events with RudderStack Swift SDK Source: https://context7.com/rudderlabs/rudder-sdk-swift/llms.txt This Swift code illustrates how to track user events using the RudderStack SDK. It covers basic event tracking, tracking events with custom properties, and tracking events with advanced options including integration control, custom context, and external identifiers. Ensure the analytics instance is initialized before calling these methods. ```swift // Basic event tracking analytics?.track(name: "Button Clicked") // Track with properties analytics?.track( name: "Product Added", properties: [ "product_id": "SKU-12345", "product_name": "Wireless Headphones", "price": 99.99, "currency": "USD", "quantity": 1 ] ) // Track with options for integration control let options = RudderOption( integrations: ["Amplitude": true, "Mixpanel": false], customContext: ["campaign": "summer_sale"], externalIds: [ExternalId(type: "brazeId", id: "braze_user_123")] ) analytics?.track( name: "Order Completed", properties: [ "order_id": "ORD-98765", "revenue": 299.99, "currency": "USD", "products": [ ["product_id": "SKU-001", "quantity": 2], ["product_id": "SKU-002", "quantity": 1] ] ], options: options ) ``` -------------------------------- ### Track Screen Views with Swift Source: https://context7.com/rudderlabs/rudder-sdk-swift/llms.txt Record screen views to understand user navigation and content engagement. Supports basic tracking, tracking with category, and tracking with custom properties. ```swift // Basic screen tracking analytics?.screen(screenName: "Home") // Track with category analytics?.screen( screenName: "Product Details", category: "Shopping" ) // Track with properties analytics?.screen( screenName: "Checkout", category: "E-commerce", properties: [ "cart_value": 149.99, "item_count": 3, "coupon_applied": true, "coupon_code": "SAVE20" ] ) ``` -------------------------------- ### Identify Users and Traits with RudderStack Swift SDK Source: https://context7.com/rudderlabs/rudder-sdk-swift/llms.txt This Swift code demonstrates how to identify users and update their traits using the RudderStack SDK. It shows basic user identification by `userId`, identifying users with associated traits (including nested company information), updating traits for anonymous users, and accessing the current user's ID and traits. Proper initialization of the analytics instance is required. ```swift // Basic user identification analytics?.identify(userId: "user_12345") // Identify with traits analytics?.identify( userId: "user_12345", traits: [ "name": "John Doe", "email": "john.doe@example.com", "phone": "+1-555-123-4567", "created_at": "2024-01-15T10:30:00Z", "plan": "premium", "company": [ "name": "Acme Inc", "employee_count": 500 ] ] ) // Update traits for anonymous user (userId is nil) analytics?.identify( userId: nil, traits: [ "preferred_language": "en", "newsletter_subscribed": true ] ) // Access current user identity let currentUserId = analytics?.userId let currentAnonymousId = analytics?.anonymousId let currentTraits = analytics?.traits ``` -------------------------------- ### Add RudderStack SDK to Package.swift (Swift) Source: https://github.com/rudderlabs/rudder-sdk-swift/blob/main/README.md This snippet shows how to add the RudderStack Swift SDK to your project's Package.swift file using Swift Package Manager. It specifies the package URL and the product to be included. ```swift // swift-tools-version:5.9 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "RudderStack", products: [ // Products define the executables and libraries a package produces, and make them visible to other packages. .library( name: "RudderStack", targets: ["RudderStack"]) ], dependencies: [ // Dependencies declare other packages that this package depends on. .package(url: "https://github.com/rudderlabs/rudder-sdk-swift.git", .upToNextMajor(from: "")) ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. // Targets can depend on other targets in this package, and on products in packages this package depends on. .target( name: "RudderStack", dependencies: [ .product(name: "RudderStackAnalytics", package: "rudder-sdk-swift") ]), .testTarget( name: "RudderStackTests", dependencies: ["RudderStack"]) ] ) ``` -------------------------------- ### Track User Actions (Swift) Source: https://github.com/rudderlabs/rudder-sdk-swift/blob/main/README.md This Swift code snippet shows how to use the `track` API of the RudderStack SDK to capture user events. It allows you to record actions performed by the user, along with associated properties like revenue and currency. ```swift analytics?.track( name: "Order Completed", properties: [ "revenue": 30.0, "currency": "USD" ] ) ``` -------------------------------- ### Send Events Immediately with Swift Source: https://context7.com/rudderlabs/rudder-sdk-swift/llms.txt Force immediate delivery of queued events to the data plane. This is often used before an application backgrounds to ensure events are sent. ```swift // Flush all pending events analytics?.flush() // Common pattern: flush before app backgrounding func applicationWillResignActive(_ application: UIApplication) { analytics?.flush() } ``` -------------------------------- ### Link User Identities with Swift Source: https://context7.com/rudderlabs/rudder-sdk-swift/llms.txt Create an alias to merge anonymous user data with identified user profiles. Supports aliasing anonymous users to known users and explicit previous ID specification. ```swift // Alias anonymous user to known user analytics?.alias( newId: "registered_user_789", previousId: nil // Uses current anonymousId if nil ) // Explicit previous ID analytics?.alias( newId: "new_user_id", previousId: "old_user_id" ) ``` -------------------------------- ### Identify User with Traits (Swift) Source: https://github.com/rudderlabs/rudder-sdk-swift/blob/main/README.md This Swift code snippet demonstrates how to use the `identify` API of the RudderStack SDK. It allows you to associate a user with specific traits, such as their name and email, using a provided user ID. ```swift analytics?.identify( userId: "1hKOmRA4el9Zt1WSfVJIVo4GRlm", traits: [ "name": "Alex Keener", "email": "alex@example.com" ] ) ``` -------------------------------- ### Associate Users with Groups with Swift Source: https://context7.com/rudderlabs/rudder-sdk-swift/llms.txt Link users to organizations or companies with associated traits. Supports basic group association and group association with custom traits. ```swift // Basic group association analytics?.group(groupId: "company_456") // Group with traits analytics?.group( groupId: "company_456", traits: [ "name": "Acme Corporation", "industry": "Technology", "employees": 1500, "plan": "enterprise", "website": "https://acme.com", "address": [ "city": "San Francisco", "state": "CA", "country": "USA" ] ] ) ``` -------------------------------- ### Track Deep Links with Swift Source: https://context7.com/rudderlabs/rudder-sdk-swift/llms.txt Track deep link opens with automatic URL parameter extraction. This function should be called in your SceneDelegate or AppDelegate when a URL is opened. ```swift // In SceneDelegate or AppDelegate func scene(_ scene: UIScene, openURLContexts URLContexts: Set) { guard let url = URLContexts.first?.url else { return } // Track deep link with automatic parameter extraction analytics?.open(url: url) // Track with additional options analytics?.open( url: url, options: [ "source": "email_campaign", "medium": "push_notification" ] ) } // Output event: "Deep Link Opened" with URL and query parameters as properties ``` -------------------------------- ### Reset User Data with Swift Source: https://context7.com/rudderlabs/rudder-sdk-swift/llms.txt Reset user identity and stored data, typically used during logout. Allows for full resets or selective resets of anonymous ID, user ID, traits, and session. ```swift // Full reset (clears all user data) analytics?.reset() // Selective reset with options let resetEntries = ResetEntries( anonymousId: true, // Generate new anonymous ID userId: true, // Clear user ID traits: true, // Clear user traits session: false // Keep current session ) let resetOptions = ResetOptions(entries: resetEntries) analytics?.reset(options: resetOptions) ``` -------------------------------- ### Shutdown Analytics Instance - Swift Source: https://context7.com/rudderlabs/rudder-sdk-swift/llms.txt Gracefully shuts down the analytics instance, saving pending events but stopping further processing. After shutdown, no new events can be tracked, but saved events will be processed on the next app launch. This is useful when the app terminates or the SDK is no longer needed. ```swift // Shutdown analytics - saves pending events but stops processing analytics?.shutdown() // Note: After shutdown, no new events can be tracked // Saved events will be processed on next app launch ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.