### Install RudderStack iOS SDK via Carthage Source: https://github.com/rudderlabs/rudder-sdk-ios/blob/develop/README.md This snippet demonstrates how to integrate the RudderStack iOS SDK into your project using Carthage. Add this line to your Cartfile and then build the framework. ```text github "rudderlabs/rudder-sdk-ios" "v1.31.1" ``` -------------------------------- ### Swift Integration Factory for Device Mode Source: https://context7.com/rudderlabs/rudder-sdk-ios/llms.txt Provides an example of implementing a custom integration factory in Swift for device mode integrations. It outlines the creation of a `CustomFactory` class conforming to `RSIntegrationFactory`, defining its `key` and `initiate` methods, and registering it with the Rudder SDK. The example also includes handling the integration ready callback. ```swift // Swift Integration Factory Implementation class CustomFactory: NSObject, RSIntegrationFactory { static let shared = CustomFactory() func key() -> String { return "Custom Destination" } func initiate(_ config: [AnyHashable: Any], client: RSClient, rudderConfig: RSConfig) -> RSIntegration { return CustomIntegration(config: config, client: client, rudderConfig: rudderConfig) } } // Register factory let builder = RSConfigBuilder() .withDataPlaneUrl("https://your-data-plane.rudderlabs.com") .withFactory(CustomFactory.shared) RSClient.getInstance("YOUR_WRITE_KEY", config: builder.build()) // Integration ready callback RSClient.sharedInstance()?.onIntegrationReady(CustomFactory.shared) { integration in print("Custom integration ready: (String(describing: integration))") } ``` -------------------------------- ### Install RudderStack iOS SDK via CocoaPods Source: https://github.com/rudderlabs/rudder-sdk-ios/blob/develop/README.md This snippet shows how to add the RudderStack iOS SDK to your project using CocoaPods. Ensure you have CocoaPods installed and configured in your project. ```ruby pod 'Rudder', '1.31.1' ``` -------------------------------- ### Manage Sessions (Objective-C, Swift) Source: https://context7.com/rudderlabs/rudder-sdk-ios/llms.txt The SDK provides manual session control for custom session tracking. Sessions are used to group user activities and understand engagement patterns. You can start sessions with auto-generated or custom IDs, end sessions, and retrieve the current session ID. ```objective-c // Objective-C Session Management // Start a new session with auto-generated ID [[RSClient sharedInstance] startSession]; // Start session with custom ID [[RSClient sharedInstance] startSession:1234567890]; // End current session [[RSClient sharedInstance] endSession]; // Get current session ID NSNumber *sessionId = [RSClient sharedInstance].sessionId; if (sessionId != nil) { NSLog(@"Current Session ID: %@", sessionId); } ``` ```swift // Swift Session Management // Start a new session RSClient.sharedInstance()?.startSession() // Start session with custom ID (e.g., timestamp-based) let customSessionId = Int(Date().timeIntervalSince1970 * 1000) RSClient.sharedInstance()?.startSession(customSessionId) // End session (e.g., on logout) RSClient.sharedInstance()?.endSession() // Access current session ID if let sessionId = RSClient.sharedInstance()?.sessionId { print("Current Session: \(sessionId)") } ``` -------------------------------- ### Enable SQLite Database Encryption (Objective-C, Swift) Source: https://context7.com/rudderlabs/rudder-sdk-ios/llms.txt Configure the Rudder SDK to encrypt sensitive event data stored locally in the SQLite database before it is uploaded. This requires creating a custom `RSDatabaseProvider` that implements encrypted database storage, for example, using SQLCipher. The encryption configuration, including the key and the custom provider, is then passed to the `RSConfigBuilder`. ```objective-c // Objective-C Database Encryption // Create encryption configuration RSDBEncryption *encryption = [[RSDBEncryption alloc] initWithKey:@"your-32-character-encryption-key" enable:YES databaseProvider:[YourEncryptedDatabaseProvider new]]; // Apply in config builder RSConfigBuilder *builder = [[RSConfigBuilder alloc] init]; [builder withDataPlaneUrl:@"https://your-data-plane.rudderlabs.com"]; [builder withDBEncryption:encryption]; [RSClient getInstance:@"YOUR_WRITE_KEY" config:[builder build]]; ``` ```swift // Swift Database Encryption // Custom database provider implementation required class EncryptedDatabaseProvider: NSObject, RSDatabaseProvider { func getDatabase(_ dbPath: String, dbEncryption: RSDBEncryption) -> RSDatabase? { // Implement encrypted database (e.g., using SQLCipher) return EncryptedDatabase(path: dbPath, key: dbEncryption.key) } } // Configure SDK with encryption let encryption = RSDBEncryption( key: "your-32-character-encryption-key", enable: true, databaseProvider: EncryptedDatabaseProvider() ) let builder = RSConfigBuilder() .withDataPlaneUrl("https://your-data-plane.rudderlabs.com") .withDBEncryption(encryption) RSClient.getInstance("YOUR_WRITE_KEY", config: builder.build()) ``` -------------------------------- ### Reset User - Objective-C Source: https://github.com/rudderlabs/rudder-sdk-ios/blob/develop/README.md Resets the current user and their associated data. This action clears all locally stored user information, effectively logging out the user or starting a new session. It takes no arguments. ```objective-c [[RSClient sharedInstance] reset]; ``` -------------------------------- ### Objective-C Integration Factory for Device Mode Source: https://context7.com/rudderlabs/rudder-sdk-ios/llms.txt Demonstrates how to implement a custom integration factory in Objective-C for device mode integrations. This involves creating a class conforming to the RSIntegrationFactory protocol, implementing the `key` and `initiate` methods, and registering the factory during SDK initialization. It also shows how to listen for the integration's readiness. ```objective-c // Objective-C Integration Factory Implementation // CustomFactory.h #import @interface CustomFactory : NSObject + (instancetype)instance; @end // CustomFactory.m @implementation CustomFactory + (instancetype)instance { static CustomFactory *sharedInstance = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ sharedInstance = [[self alloc] init]; }); return sharedInstance; } - (NSString *)key { return @"Custom Destination"; } - (id)initiate:(NSDictionary *)config client:(RSClient *)client rudderConfig:(RSConfig *)rudderConfig { return [[CustomIntegration alloc] initWithConfig:config client:client rudderConfig:rudderConfig]; } @end // Register factory during SDK init RSConfigBuilder *builder = [[RSConfigBuilder alloc] init]; [builder withDataPlaneUrl:@"https://your-data-plane.rudderlabs.com"]; [builder withFactory:[CustomFactory instance]]; [RSClient getInstance:@"YOUR_WRITE_KEY" config:[builder build]]; // Listen for integration ready callback [[RSClient sharedInstance] onIntegrationReady:[CustomFactory instance] withCallback:^(NSObject * _Nullable integration) { NSLog(@"Custom integration is ready: %@", integration); }]; ``` -------------------------------- ### Initialize RudderStack SDK in Swift Source: https://context7.com/rudderlabs/rudder-sdk-ios/llms.txt Initializes the RudderStack SDK using a builder pattern for configuration in Swift. It requires a write key and data/control plane URLs, and allows setting various SDK parameters like log level, flush queue size, and lifecycle event tracking. ```swift // Swift Initialization import Rudder func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { let builder = RSConfigBuilder() .withDataPlaneUrl("https://your-data-plane.rudderlabs.com") .withControlPlaneUrl("https://api.rudderlabs.com") .withLoglevel(RSLogLevelDebug) .withFlushQueueSize(30) .withDBCountThreshold(10000) .withSleepTimeOut(10) .withSessionTimeoutMillis(300000) .withTrackLifecycleEvens(true) .withRecordScreenViews(true) .withEnableBackgroundMode(true) .withAutoSessionTracking(true) .withCollectDeviceId(true) .withGzip(true) RSClient.getInstance("YOUR_WRITE_KEY", config: builder.build()) // Access shared instance anywhere in your app let client = RSClient.sharedInstance() return true } ``` -------------------------------- ### Initialize RudderStack SDK in Objective-C Source: https://context7.com/rudderlabs/rudder-sdk-ios/llms.txt Initializes the RudderStack SDK using a builder pattern for configuration in Objective-C. It requires a write key and data/control plane URLs, and allows setting various SDK parameters like log level, flush queue size, and lifecycle event tracking. ```objective-c // Objective-C Initialization #import - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { RSConfigBuilder *builder = [[RSConfigBuilder alloc] init]; [builder withDataPlaneUrl:@"https://your-data-plane.rudderlabs.com"]; [builder withControlPlaneUrl:@"https://api.rudderlabs.com"]; [builder withLoglevel:RSLogLevelDebug]; [builder withFlushQueueSize:30]; [builder withDBCountThreshold:10000]; [builder withSleepTimeOut:10]; [builder withSessionTimeoutMillis:300000]; [builder withTrackLifecycleEvens:YES]; [builder withRecordScreenViews:YES]; [builder withEnableBackgroundMode:YES]; [builder withAutoSessionTracking:YES]; [builder withCollectDeviceId:YES]; [builder withGzip:YES]; [RSClient getInstance:@"YOUR_WRITE_KEY" config:[builder build]]; // Access shared instance anywhere in your app RSClient *client = [RSClient sharedInstance]; return YES; } ``` -------------------------------- ### Send a screen event with properties Source: https://github.com/rudderlabs/rudder-sdk-ios/blob/develop/README.md This Objective-C snippet demonstrates how to send a screen event, which is typically used to track which screen a user is viewing in your application. It can include properties to describe the screen. ```objectivec [[RSClient sharedInstance] screen:@"Main" properties:@{@"prop_key" : @"prop_value"}]; ``` -------------------------------- ### Initialize RudderStack Client in AppDelegate Source: https://github.com/rudderlabs/rudder-sdk-ios/blob/develop/README.md This Objective-C code initializes the RudderStack client (`RSClient`) in your application's `AppDelegate.m` file. It requires your Data Plane URL and Write Key. ```objectivec RSConfigBuilder *builder = [[RSConfigBuilder alloc] init]; [builder withDataPlaneUrl:]; [RSClient getInstance: config:[builder build]]; ``` -------------------------------- ### Track Screen Views with Properties and Options in Objective-C and Swift Source: https://context7.com/rudderlabs/rudder-sdk-ios/llms.txt The `screen` method tracks screen or page views in your application, helping you understand user navigation patterns. It can include properties to detail the screen content and options to control integration behavior. ```objective-c // Objective-C Screen Examples // Simple screen view [[RSClient sharedInstance] screen:@"Home"]; // Screen with properties [[RSClient sharedInstance] screen:@"Product Details" properties:@{ @"product_id": @"SKU-12345", @"product_name": @"Wireless Headphones", @"category": @"Electronics", @"referrer": @"search_results", @"search_query": @"bluetooth headphones" }]; // Screen with options RSOption *option = [[RSOption alloc] init]; [option putIntegration:@"Google Analytics" isEnabled:YES]; [[RSClient sharedInstance] screen:@"Checkout" properties:@{@"step": @1, @"cart_value": @199.99} options:option]; ``` ```swift // Swift Screen Examples // Simple screen view RSClient.sharedInstance()?.screen("Home") // Screen with properties RSClient.sharedInstance()?.screen("Product Details", properties: [ "product_id": "SKU-12345", "product_name": "Wireless Headphones", "category": "Electronics", "price": 149.99, "in_stock": true ]) // Screen with navigation context RSClient.sharedInstance()?.screen("Settings", properties: [ "previous_screen": "Profile", "navigation_method": "tab_bar", "time_on_previous_screen": 45.5 ]) ``` -------------------------------- ### Set Device Token and Advertising ID (Objective-C, Swift) Source: https://context7.com/rudderlabs/rudder-sdk-ios/llms.txt Configure device tokens for push notifications and advertising IDs for attribution tracking. These can be set using static methods before SDK initialization or via instance methods after initialization. The advertising ID can also be cleared if the user opts out of ad tracking. Includes handling of APNS device tokens and requesting IDFA with App Tracking Transparency. ```objective-c // Objective-C Device Token and Advertising ID // Set before SDK initialization (static methods) [RSClient putDeviceToken:@"your-apns-device-token"]; [RSClient putAdvertisingId:@"your-idfa-advertising-id"]; [RSClient putAnonymousId:@"custom-anonymous-id"]; [RSClient putAuthToken:@"your-auth-token"]; // After initialization, clear advertising ID if needed [[RSClient sharedInstance] clearAdvertisingId]; // Example: Setting device token from push notification registration - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken { NSMutableString *token = [NSMutableString string]; const unsigned char *bytes = (const unsigned char *)deviceToken.bytes; for (NSUInteger i = 0; i < deviceToken.length; i++) { [token appendFormat:@"%%02x", bytes[i]]; } [RSClient putDeviceToken:token]; } ``` ```swift // Swift Device Token and Advertising ID // Set before initialization RSClient.putDeviceToken("your-apns-device-token") RSClient.putAdvertisingId("your-idfa-advertising-id") RSClient.putAnonymousId("custom-anonymous-id") // Clear advertising ID (e.g., when user opts out of ad tracking) RSClient.sharedInstance()?.clearAdvertisingId() // Handle push notification registration func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { let token = deviceToken.map { String(format: "%02.2hhx", $0) }.joined() RSClient.putDeviceToken(token) } // Get IDFA with App Tracking Transparency import AppTrackingTransparency import AdSupport func requestTrackingPermission() { if #available(iOS 14, *) { ATTrackingManager.requestTrackingAuthorization { status in if status == .authorized { let idfa = ASIdentifierManager.shared().advertisingIdentifier.uuidString RSClient.putAdvertisingId(idfa) } } } else { let idfa = ASIdentifierManager.shared().advertisingIdentifier.uuidString RSClient.putAdvertisingId(idfa) } } ``` -------------------------------- ### Import RudderStack SDK Header Source: https://github.com/rudderlabs/rudder-sdk-ios/blob/develop/README.md Include this import statement in your Objective-C files (.m and .h) to use the RudderStack SDK classes. This is a prerequisite for using the SDK's functionalities. ```objectivec #import ``` -------------------------------- ### Send a simple track event Source: https://github.com/rudderlabs/rudder-sdk-ios/blob/develop/README.md This Objective-C snippet demonstrates how to send a basic track event using the RudderStack SDK. This is useful for logging simple user actions without additional properties. ```objectivec [[RSClient sharedInstance] track:@"simple_track_event"]; ``` -------------------------------- ### Send a track event with properties Source: https://github.com/rudderlabs/rudder-sdk-ios/blob/develop/README.md This Objective-C code shows how to send a track event with associated properties. Properties provide additional context to the event, such as values or metadata. ```objectivec [[RSClient sharedInstance] track:@"simple_track_with_props" properties:@{ @"key_1" : @"value_1", @"key_2" : @"value_2" }]; ``` -------------------------------- ### Configure RudderStack SDK via Swift Package Manager Source: https://github.com/rudderlabs/rudder-sdk-ios/blob/develop/README.md This Swift code snippet shows how to add the RudderStack iOS SDK as a dependency in your project's `Package.swift` file using Swift Package Manager. It specifies the repository URL and version constraint. ```swift // swift-tools-version:5.5 // 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: "git@github.com:rudderlabs/rudder-sdk-ios.git", from: "1.31.1") ], 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: "Rudder", package: "rudder-sdk-ios") ]), .testTarget( name: "RudderStackTests", dependencies: ["RudderStack"]), ] ) ``` -------------------------------- ### Configure Data Residency (Objective-C, Swift) Source: https://context7.com/rudderlabs/rudder-sdk-ios/llms.txt Set the data residency for the Rudder SDK to comply with regional data regulations, such as those in the EU or US. This is done by calling `withDataResidencyServer` on the `RSConfigBuilder` with the appropriate enum value (`EU` or `US`). The data plane URL must also be configured. ```objective-c // Objective-C Data Residency RSConfigBuilder *builder = [[RSConfigBuilder alloc] init]; // Set data residency to EU [builder withDataResidencyServer:EU]; // Or US [builder withDataResidencyServer:US]; [builder withDataPlaneUrl:@"https://your-data-plane.rudderlabs.com"]; [RSClient getInstance:@"YOUR_WRITE_KEY" config:[builder build]]; ``` ```swift // Swift Data Residency let builder = RSConfigBuilder() .withDataResidencyServer(EU) // or US .withDataPlaneUrl("https://your-data-plane.rudderlabs.com") .withControlPlaneUrl("https://api.rudderlabs.com") RSClient.getInstance("YOUR_WRITE_KEY", config: builder.build()) ``` -------------------------------- ### Identify Users with Traits and Options in Objective-C and Swift Source: https://context7.com/rudderlabs/rudder-sdk-ios/llms.txt The `identify` method associates user data and traits with subsequent events. It can be called with just a user ID, or with additional traits and integration options. Call this after user login or when user profile information changes. ```objective-c // Objective-C Identify Examples // Simple identify with user ID [[RSClient sharedInstance] identify:@"user_12345"]; // Identify with traits [[RSClient sharedInstance] identify:@"user_12345" traits:@{ @"email": @"john.doe@example.com", @"name": @"John Doe", @"phone": @"+1-555-123-4567", @"age": @28, @"plan": @"premium", @"created_at": @"2024-01-15T10:30:00Z", @"company": @{ @"id": @"company_456", @"name": @"Acme Corp", @"industry": @"Technology" }, @"address": @{ @"city": @"San Francisco", @"state": @"CA", @"country": @"USA" } }]; // Identify with options RSOption *option = [[RSOption alloc] init]; [option putExternalId:@"Firebase" withId:@"firebase_user_id"]; [option putCustomContext:@{@"subscription_tier": @"gold"} withKey:@"app_context"]; [[RSClient sharedInstance] identify:@"user_12345" traits:@{@"email": @"john@example.com"} options:option]; ``` ```swift // Swift Identify Examples // Simple identify RSClient.sharedInstance()?.identify("user_12345") // Identify with comprehensive traits RSClient.sharedInstance()?.identify("user_12345", traits: [ "email": "john.doe@example.com", "name": "John Doe", "phone": "+1-555-123-4567", "age": 28, "plan": "premium", "avatar_url": URL(string: "https://example.com/avatar.jpg")!, "signup_date": Date(), "preferences": [ "notifications": true, "newsletter": false, "theme": "dark" ] ]) // Anonymous identify (update traits without user ID) RSClient.sharedInstance()?.identify(nil, traits: [ "anonymous_trait": "visitor_preference" ]) ``` -------------------------------- ### Group Users with Traits and Options in Objective-C and Swift Source: https://context7.com/rudderlabs/rudder-sdk-ios/llms.txt The `group` method associates users with a company, organization, or any group entity, useful for B2B applications to track account-level data. It accepts a group ID and can include traits and integration options. ```objective-c // Objective-C Group Examples // Simple group [[RSClient sharedInstance] group:@"company_12345"]; // Group with traits [[RSClient sharedInstance] group:@"company_12345" traits:@{ @"name": @"Acme Corporation", @"industry": @"Technology", @"employees": @500, @"plan": @"enterprise", @"monthly_spend": @4999.99, @"created_at": @"2020-06-15", @"address": @{ @"city": @"San Francisco", @"state": @"CA", @"country": @"USA" } }]; // Group with options RSOption *option = [[RSOption alloc] init]; [option putIntegration:@"Intercom" isEnabled:YES]; [[RSClient sharedInstance] group:@"team_789" traits:@{@"team_name": @"Engineering", @"size": @25} options:option]; ``` ```swift // Swift Group Examples // Simple group RSClient.sharedInstance()?.group("company_12345") // Group with comprehensive traits RSClient.sharedInstance()?.group("company_12345", traits: [ "name": "Acme Corporation", "industry": "Technology", "employees": 500, "plan": "enterprise", "website": "https://acme.example.com", "founded": 2015, "features_enabled": ["analytics", "api_access", "sso"] ]) ``` -------------------------------- ### Control Destination Routing with RSOption in Objective-C and Swift Source: https://context7.com/rudderlabs/rudder-sdk-ios/llms.txt Provides granular control over which destinations receive events and allows for attaching external IDs or custom contexts. This is useful for managing data flow to different analytics platforms and for identity resolution. The RSOption object can be configured with specific integrations, external identifiers, and custom context data. ```objective-c // Objective-C RSOption Usage RSOption *option = [[RSOption alloc] init]; // Enable/disable specific integrations [option putIntegration:@"Amplitude" isEnabled:YES]; [option putIntegration:@"Mixpanel" isEnabled:NO]; [option putIntegration:@"Google Analytics" isEnabled:YES]; [option putIntegration:@"All" isEnabled:NO]; // Disable all by default // Add external IDs for cross-platform identity [option putExternalId:@"brazeExternalId" withId:@"braze_123"]; [option putExternalId:@"firebaseUserId" withId:@"firebase_456"]; [option putExternalId:@"intercomId" withId:@"intercom_789"]; // Add custom context [option putCustomContext:@{ @"campaign": @"summer_sale", @"source": @"email", @"experiment_variant": @"B" } withKey:@"marketing"]; [option putCustomContext:@{ @"app_version": @"2.5.0", @"build_number": @"1234" } withKey:@"app_info"]; // Use with any tracking call [[RSClient sharedInstance] track:@"Purchase Completed" properties:@{@"value": @99.99} options:option]; ``` ```swift // Swift RSOption Usage let option = RSOption() // Control destination routing option.putIntegration("Amplitude", isEnabled: true) option.putIntegration("Mixpanel", isEnabled: false) option.putIntegration("All", isEnabled: false) // Start with all disabled // Attach external identifiers option.putExternalId("brazeExternalId", withId: "braze_123") option.putExternalId("firebaseUserId", withId: "firebase_456") // Add custom context data option.putCustomContext([ "campaign": "summer_sale", "source": "push_notification", "ab_test": "variant_a" ], withKey: "marketing") // Apply to track call RSClient.sharedInstance()?.track("Button Clicked", properties: [ "button_name": "Buy Now" ], options: option) // Apply to identify call RSClient.sharedInstance()?.identify("user_123", traits: [ "email": "user@example.com" ], options: option) ``` -------------------------------- ### Implement GDPR Opt-Out Control in Objective-C and Swift Source: https://context7.com/rudderlabs/rudder-sdk-ios/llms.txt Enables GDPR-compliant data collection by allowing users to opt out of tracking entirely. This functionality is crucial for privacy regulations. It includes methods to opt out, opt back in, and handle user preference changes, ensuring data collection respects user consent. ```objective-c // Objective-C Opt Out // Opt out of all tracking [[RSClient sharedInstance] optOut:YES]; // Opt back in to tracking [[RSClient sharedInstance] optOut:NO]; // Implement user preference handling - (void)handlePrivacyPreferenceChange:(BOOL)allowTracking { if (allowTracking) { [[RSClient sharedInstance] optOut:NO]; [[RSClient sharedInstance] track:@"Tracking Enabled"]; } else { [[RSClient sharedInstance] track:@"Tracking Disabled"]; [[RSClient sharedInstance] flush]; [[RSClient sharedInstance] optOut:YES]; } } ``` ```swift // Swift Opt Out // Disable all tracking RSClient.sharedInstance()?.optOut(true) // Re-enable tracking RSClient.sharedInstance()?.optOut(false) // Privacy settings implementation func updatePrivacySettings(analyticsEnabled: Bool) { if analyticsEnabled { RSClient.sharedInstance()?.optOut(false) RSClient.sharedInstance()?.track("Privacy Settings Updated", properties: [ "analytics_enabled": true ]) } else { // Send final event before opt-out RSClient.sharedInstance()?.track("Privacy Settings Updated", properties: [ "analytics_enabled": false ]) RSClient.sharedInstance()?.flush() RSClient.sharedInstance()?.optOut(true) } } ``` -------------------------------- ### Send an identify event with traits Source: https://github.com/rudderlabs/rudder-sdk-ios/blob/develop/README.md This Objective-C code shows how to send an identify event, used to associate a user ID with traits (user properties). This helps in building user profiles and understanding user behavior. ```objectivec [[RSClient sharedInstance] identify:@"test_user_id" traits:@{@"foo": @"bar", @"foo1": @"bar1", @"email": @"test@gmail.com"} ]; ``` -------------------------------- ### Track Deep Links with RudderStack iOS SDK Source: https://context7.com/rudderlabs/rudder-sdk-ios/llms.txt Implement deep link and universal link tracking to capture attribution data and analyze user journeys. This involves integrating the `RSClient`'s `openURL` method within your application's delegate methods for handling incoming URLs. ```objective-c // Objective-C Deep Link Tracking // In AppDelegate for URL schemes (iOS 12 and below) - (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary *)options { [[RSClient sharedInstance] openURL:url options:options]; return YES; } // Simple URL tracking without options - (BOOL)application:(UIApplication *)app openURL:(NSURL *)url { [[RSClient sharedInstance] openURL:url]; return YES; } // For Universal Links in SceneDelegate - (void)scene:(UIScene *)scene continueUserActivity:(NSUserActivity *)userActivity { if ([userActivity.activityType isEqualToString:NSUserActivityTypeBrowsingWeb]) { NSURL *url = userActivity.webpageURL; [[RSClient sharedInstance] openURL:url]; } } ``` ```swift // Swift Deep Link Tracking // SceneDelegate for iOS 13+ func scene(_ scene: UIScene, openURLContexts URLContexts: Set) { guard let urlContext = URLContexts.first else { return } RSClient.sharedInstance()?.openURL(urlContext.url, options: [:]) } // Universal Links func scene(_ scene: UIScene, continue userActivity: NSUserActivity) { if userActivity.activityType == NSUserActivityTypeBrowsingWeb, let url = userActivity.webpageURL { RSClient.sharedInstance()?.openURL(url) } } // AppDelegate for iOS 12 and below func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool { RSClient.sharedInstance()?.openURL(url, options: options) return true } ``` -------------------------------- ### Access RudderStack iOS SDK Properties Source: https://context7.com/rudderlabs/rudder-sdk-ios/llms.txt Retrieve essential SDK properties such as anonymous ID, session ID, context details, and configuration parameters after the SDK has been initialized. This allows for dynamic access to user and application state. ```objective-c // Objective-C Property Access RSClient *client = [RSClient sharedInstance]; // Get anonymous ID NSString *anonymousId = client.anonymousId; NSLog(@"Anonymous ID: %@", anonymousId); // Get current session ID NSNumber *sessionId = client.sessionId; NSLog(@"Session ID: %@", sessionId); // Get SDK configuration RSConfig *config = client.config; NSLog(@"Data Plane URL: %@", config.dataPlaneUrl); NSLog(@"Flush Queue Size: %d", config.flushQueueSize); // Get context information RSContext *context = client.context; NSLog(@"Device ID: %@", context.device.identifier); NSLog(@"App Version: %@", context.app.version); NSLog(@"OS Version: %@", context.os.version); // Get default options RSOption *defaultOptions = client.defaultOptions; ``` ```swift // Swift Property Access guard let client = RSClient.sharedInstance() else { return } // Anonymous ID if let anonymousId = client.anonymousId { print("Anonymous ID: \(anonymousId)") } // Session ID if let sessionId = client.sessionId { print("Session ID: \(sessionId)") } // Configuration if let config = client.config { print("Data Plane: \(config.dataPlaneUrl ?? "not set")") print("Flush Size: \(config.flushQueueSize)") print("Log Level: \(config.logLevel)") print("Lifecycle Tracking: \(config.trackLifecycleEvents)") } // Context information let context = client.context print("Device: \(context.device.model ?? "unknown")") print("OS: \(context.os.name ?? "unknown") \(context.os.version ?? "")") print("App: \(context.app.name ?? "unknown") v\(context.app.version ?? "")") print("Timezone: \(context.timezone ?? "unknown")") print("Locale: \(context.locale ?? "unknown")") ``` -------------------------------- ### Track User Events with RudderStack SDK Source: https://context7.com/rudderlabs/rudder-sdk-ios/llms.txt Records user actions and events with optional properties and destination control using the RudderStack SDK. This method is used to capture meaningful user interactions like button clicks, purchases, or feature usage. ```objective-c // Objective-C Track Examples // Simple track event [[RSClient sharedInstance] track:@"Button Clicked"]; // Track with properties [[RSClient sharedInstance] track:@"Product Purchased" properties:@{ @"product_id": @"SKU-12345", @"product_name": @"Premium Subscription", @"price": @99.99, @"currency": @"USD", @"quantity": @1, @"category": @"Subscriptions" }]; // Track with options for destination control RSOption *option = [[RSOption alloc] init]; [option putIntegration:@"Amplitude" isEnabled:YES]; [option putIntegration:@"Mixpanel" isEnabled:NO]; [option putExternalId:@"brazeExternalId" withId:@"user_braze_123"]; [[RSClient sharedInstance] track:@"Order Completed" properties:@{@"order_id": @"ORD-789", @"total": @149.99} options:option]; ``` ```swift // Swift Track Examples // Simple track event RSClient.sharedInstance()?.track("Button Clicked") // Track with properties RSClient.sharedInstance()?.track("Product Purchased", properties: [ "product_id": "SKU-12345", "product_name": "Premium Subscription", "price": 99.99, "currency": "USD", "quantity": 1, "category": "Subscriptions", "is_gift": false, "tags": ["featured", "best-seller"] ]) // Track with complex nested properties RSClient.sharedInstance()?.track("Checkout Completed", properties: [ "order_id": "ORD-789", "total": 149.99, "products": [ ["id": "P1", "name": "Item 1", "price": 49.99], ["id": "P2", "name": "Item 2", "price": 100.00] ], "timestamp": Date() ]) ``` -------------------------------- ### Alias User Identities (Objective-C, Swift) Source: https://context7.com/rudderlabs/rudder-sdk-ios/llms.txt The alias method links two user identities. It's typically used when a user transitions from an anonymous to an identified state or when their user ID changes. It supports aliasing with or without a previous ID and can include integration-specific options. ```objective-c // Objective-C Alias Examples // Simple alias - links new ID to current user [[RSClient sharedInstance] alias:@"new_user_id"]; // Alias with explicit previous ID [[RSClient sharedInstance] alias:@"new_user_id" previousId:@"old_user_id" options:nil]; // Alias with options RSOption *option = [[RSOption alloc] init]; [option putIntegration:@"Mixpanel" isEnabled:YES]; [[RSClient sharedInstance] alias:@"authenticated_user_123" previousId:@"anonymous_visitor_456" options:option]; ``` ```swift // Swift Alias Examples // Simple alias RSClient.sharedInstance()?.alias("new_user_id") // Alias with options let option = RSOption() option.putIntegration("Amplitude", isEnabled: true) RSClient.sharedInstance()?.alias("authenticated_user_123", options: option) ``` -------------------------------- ### Objective-C Consent Filter for RudderStack iOS SDK Source: https://context7.com/rudderlabs/rudder-sdk-ios/llms.txt Implements a consent filter using Objective-C for the RudderStack iOS SDK. This filter controls which destinations receive data based on user consent preferences. It requires a custom implementation of the `RSConsentFilter` protocol. ```objective-c // Objective-C Consent Filter // ConsentFilter.h #import @interface ConsentFilter : NSObject @end // ConsentFilter.m @implementation ConsentFilter - (NSDictionary *)filterConsentedDestinations:(NSArray *)destinations { NSMutableDictionary *consentedDestinations = [NSMutableDictionary new]; // Get user consent preferences from your consent management platform NSArray *consentedCategories = [self getUserConsentedCategories]; for (RSServerDestination *destination in destinations) { // Check if destination requires consent BOOL isConsented = [self checkConsent:destination.destinationDefinition.displayName categories:consentedCategories]; consentedDestinations[destination.destinationDefinition.displayName] = @(isConsented); } return consentedDestinations; } - (NSDictionary *)getConsentCategoriesDict { return @{ @"analytics": @YES, @"advertising": @NO, @"functional": @YES }; } @end // Usage in SDK init RSConfigBuilder *builder = [[RSConfigBuilder alloc] init]; [builder withConsentFilter:[ConsentFilter new]]; ``` -------------------------------- ### Swift Consent Filter for RudderStack iOS SDK Source: https://context7.com/rudderlabs/rudder-sdk-ios/llms.txt Implements a consent filter using Swift for the RudderStack iOS SDK. This filter determines data destination based on user consent. It adheres to the `RSConsentFilter` protocol and requires custom logic for checking user consent. ```swift // Swift Consent Filter class ConsentFilter: NSObject, RSConsentFilter { func filterConsentedDestinations(_ destinations: [RSServerDestination]) -> [String: NSNumber]? { var consentedDestinations: [String: NSNumber] = [:] // Check consent for each destination for destination in destinations { let destinationName = destination.destinationDefinition?.displayName ?? "" let isConsented = checkUserConsent(for: destinationName) consentedDestinations[destinationName] = NSNumber(value: isConsented) } return consentedDestinations } func getConsentCategoriesDict() -> [String: NSNumber]? { // Return current consent status by category return [ "analytics": NSNumber(value: UserDefaults.standard.bool(forKey: "consent_analytics")), "advertising": NSNumber(value: UserDefaults.standard.bool(forKey: "consent_ads")), "functional": NSNumber(value: true) ] } private func checkUserConsent(for destination: String) -> Bool { // Implement your consent checking logic return true } } // Apply consent filter let builder = RSConfigBuilder() .withDataPlaneUrl("https://your-data-plane.rudderlabs.com") .withConsentFilter(ConsentFilter()) ``` -------------------------------- ### Group User - Objective-C Source: https://github.com/rudderlabs/rudder-sdk-ios/blob/develop/README.md Groups a user into a specified group. This function requires a group ID and a dictionary of traits associated with the group. It's used to segment users based on shared characteristics or affiliations. ```objective-c [[RSClient sharedInstance] group:@"sample_group_id" traits:@{@"foo": @"bar", @"foo1": @"bar1", @"email": @"test@gmail.com"} ]; ``` -------------------------------- ### Reset User Data and Flush Events (Objective-C, Swift) Source: https://context7.com/rudderlabs/rudder-sdk-ios/llms.txt The reset method clears user identity data, which is useful during logout. The flush method forces an immediate upload of all queued events to the server. Reset can optionally clear the anonymous ID as well. ```objective-c // Objective-C Reset and Flush // Reset user data but keep anonymous ID [[RSClient sharedInstance] reset:NO]; // Full reset including anonymous ID [[RSClient sharedInstance] reset:YES]; // Force flush all queued events to server [[RSClient sharedInstance] flush]; // Typical logout flow - (void)handleUserLogout { // Track logout event before reset [[RSClient sharedInstance] track:@"User Logged Out"]; // Flush to ensure logout event is sent [[RSClient sharedInstance] flush]; // Reset user data [[RSClient sharedInstance] reset:YES]; // End session [[RSClient sharedInstance] endSession]; } ``` ```swift // Swift Reset and Flush // Reset user data, keep anonymous ID RSClient.sharedInstance()?.reset(false) // Full reset including anonymous ID (for complete user switch) RSClient.sharedInstance()?.reset(true) // Force flush queued events RSClient.sharedInstance()?.flush() // Complete logout implementation func handleUserLogout() { // Track and send logout event RSClient.sharedInstance()?.track("User Logged Out", properties: [ "logout_time": Date(), "session_duration": calculateSessionDuration() ]) // Ensure event is sent before reset RSClient.sharedInstance()?.flush() // Clear all user data RSClient.sharedInstance()?.reset(true) // End current session RSClient.sharedInstance()?.endSession() } ``` -------------------------------- ### Alias User - Objective-C Source: https://github.com/rudderlabs/rudder-sdk-ios/blob/develop/README.md Associates an anonymous user with a new user ID. This is useful for merging user data when a user transitions from an anonymous state to a logged-in state. It takes the new user ID as an argument. ```objective-c [[RSClient sharedInstance] alias:@"new_user_id"]; ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.