### Initialize SensorsAnalyticsSDK Source: https://context7.com/sensorsdata/sa-sdk-ios/llms.txt Configure and start the SDK within the application:didFinishLaunchingWithOptions: method. Ensure the server URL is set correctly to point to your data collection endpoint. ```objectivec // Objective-C 初始化示例 #import - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // 创建配置对象,设置数据接收服务器地址 NSString *serverURL = @"https://your-server.sensorsdata.cn/sa?project=default"; SAConfigOptions *options = [[SAConfigOptions alloc] initWithServerURL:serverURL launchOptions:launchOptions]; // 配置自动采集事件类型:App 启动、退出、点击、页面浏览 options.autoTrackEventType = SensorsAnalyticsEventTypeAppStart | SensorsAnalyticsEventTypeAppEnd | SensorsAnalyticsEventTypeAppClick | SensorsAnalyticsEventTypeAppViewScreen; // 网络策略:WiFi 和蜂窝网络下都发送数据 options.flushNetworkPolicy = SensorsAnalyticsNetworkTypeWIFI | SensorsAnalyticsNetworkType3G | SensorsAnalyticsNetworkType4G; // 数据发送配置 options.flushInterval = 15000; // 发送间隔:15 秒 options.flushBulkSize = 100; // 缓存条数阈值:100 条 options.maxCacheSize = 10000; // 最大缓存条数:10000 条 // 开启功能开关 options.enableHeatMap = YES; // 热力图 options.enableVisualizedAutoTrack = YES; // 可视化全埋点 options.enableJavaScriptBridge = YES; // H5 打通 options.enableLog = YES; // 调试日志 // 启动 SDK [SensorsAnalyticsSDK startWithConfigOptions:options]; return YES; } ``` ```swift // Swift 初始化示例 import SensorsAnalyticsSDK func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { let serverURL = "https://your-server.sensorsdata.cn/sa?project=default" let options = SAConfigOptions(serverURL: serverURL, launchOptions: launchOptions) // 配置自动采集事件类型 options.autoTrackEventType = [.eventTypeAppStart, .eventTypeAppEnd, .eventTypeAppClick, .eventTypeAppViewScreen] // 配置参数 options.enableVisualizedAutoTrack = true options.enableHeatMap = true options.maxCacheSize = 10000 // 启动 SDK SensorsAnalyticsSDK.start(configOptions: options) return true } ``` -------------------------------- ### Track Event Duration Source: https://context7.com/sensorsdata/sa-sdk-ios/llms.txt Measure the duration of events using start, pause, resume, and end timers. ```objectivec // 场景:统计视频播放时长 // 开始播放 NSString *eventId = [[SensorsAnalyticsSDK sharedInstance] trackTimerStart:@"VideoPlay"]; NSLog(@"开始计时,eventId: %@", eventId); // ... 用户观看视频 ... // 暂停播放(暂停计时) [[SensorsAnalyticsSDK sharedInstance] trackTimerPause:@"VideoPlay"]; // 继续播放(恢复计时) [[SensorsAnalyticsSDK sharedInstance] trackTimerResume:@"VideoPlay"]; // 结束播放(发送事件,携带 event_duration) [[SensorsAnalyticsSDK sharedInstance] trackTimerEnd:@"VideoPlay" withProperties:@{ @"video_id": @"VID_12345", @"video_title": @"iOS 开发教程", @"play_type": @"完整播放" }]; // 交叉计时场景(同时追踪多个同名事件) NSString *timer1 = [[SensorsAnalyticsSDK sharedInstance] trackTimerStart:@"PageView"]; NSString *timer2 = [[SensorsAnalyticsSDK sharedInstance] trackTimerStart:@"PageView"]; // 使用 eventId 区分不同计时 [[SensorsAnalyticsSDK sharedInstance] trackTimerEnd:timer1 withProperties:@{@"page": @"首页"}]; [[SensorsAnalyticsSDK sharedInstance] trackTimerEnd:timer2 withProperties:@{@"page": @"详情页"}]; // 删除指定计时器 [[SensorsAnalyticsSDK sharedInstance] removeTimer:@"VideoPlay"]; // 清除所有计时器 [[SensorsAnalyticsSDK sharedInstance] clearTrackTimer]; ``` -------------------------------- ### Handle URL Scheme and Universal Links Source: https://context7.com/sensorsdata/sa-sdk-ios/llms.txt Process incoming URLs to handle scenarios like QR code scanning for debugging or DeepLinking. Implement this in your `AppDelegate` to allow the SDK to intercept and handle relevant URLs. ```objectivec // 在 AppDelegate 中处理 URL - (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary *)options { // 判断是否为神策 SDK 可处理的 URL if ([[SensorsAnalyticsSDK sharedInstance] canHandleURL:url]) { [[SensorsAnalyticsSDK sharedInstance] handleSchemeUrl:url]; return YES; } // 处理其他业务 URL return NO; } // 处理 Universal Link - (BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void (^)(NSArray> *))restorationHandler { if ([[SensorsAnalyticsSDK sharedInstance] canHandleURL:userActivity.webpageURL]) { [[SensorsAnalyticsSDK sharedInstance] handleSchemeUrl:userActivity.webpageURL]; } return YES; } ``` -------------------------------- ### Control SDK Status and Logging Source: https://context7.com/sensorsdata/sa-sdk-ios/llms.txt Manage the SDK's operational state by enabling or disabling it, controlling log output, and accessing SDK version and preset properties. Also includes functionality to clear Keychain data. ```objectivec // 禁用 SDK(停止采集和发送数据) [SensorsAnalyticsSDK disableSDK]; ``` ```objectivec // 启用 SDK(恢复数据采集功能) [SensorsAnalyticsSDK enableSDK]; ``` ```objectivec // 开启/关闭日志 [[SensorsAnalyticsSDK sharedInstance] enableLog:YES]; ``` ```objectivec // 获取 SDK 版本号 NSString *version = [[SensorsAnalyticsSDK sharedInstance] libVersion]; NSLog(@"SDK 版本: %@", version); ``` ```objectivec // 获取预置属性 NSDictionary *presetProperties = [[SensorsAnalyticsSDK sharedInstance] getPresetProperties]; NSLog(@"预置属性: %@", presetProperties); ``` ```objectivec // 清除 Keychain 数据(包括 distinct_id) [[SensorsAnalyticsSDK sharedInstance] clearKeychainData]; ``` -------------------------------- ### Configure Public Super Properties Source: https://context7.com/sensorsdata/sa-sdk-ios/llms.txt Register static or dynamic properties that are automatically included with every tracked event. ```objectivec // 注册静态公共属性 [[SensorsAnalyticsSDK sharedInstance] registerSuperProperties:@{ @"app_version": @"2.5.0", @"platform": @"iOS", @"device_id": [UIDevice currentDevice].identifierForVendor.UUIDString }]; // 注册动态公共属性(每次触发事件时动态获取) [[SensorsAnalyticsSDK sharedInstance] registerDynamicSuperProperties:^NSDictionary * _Nonnull{ // 获取当前网络状态、App 状态等动态信息 __block UIApplicationState appState; if ([NSThread isMainThread]) { appState = [UIApplication sharedApplication].applicationState; } else { dispatch_sync(dispatch_get_main_queue(), ^{ appState = [UIApplication sharedApplication].applicationState; }); } return @{ @"app_state": appState == UIApplicationStateActive ? @"前台" : @"后台", @"current_time": @([[NSDate date] timeIntervalSince1970]) }; }]; // 获取当前公共属性 NSDictionary *superProps = [[SensorsAnalyticsSDK sharedInstance] currentSuperProperties]; NSLog(@"当前公共属性: %@", superProps); // 删除指定公共属性 [[SensorsAnalyticsSDK sharedInstance] unregisterSuperProperty:@"temp_property"]; // 清除所有公共属性 [[SensorsAnalyticsSDK sharedInstance] clearSuperProperties]; ``` -------------------------------- ### Implement Custom Property Plugin Source: https://context7.com/sensorsdata/sa-sdk-ios/llms.txt Create and register custom property plugins to dynamically add attributes to events. The plugin can define its priority, filter which events it applies to, and return the properties to be added. ```objectivec // 创建自定义属性插件 @interface MyPropertyPlugin : SAPropertyPlugin @end @implementation MyPropertyPlugin // 设置插件优先级 - (SAPropertyPluginPriority)priority { return SAPropertyPluginPriorityHigh; // 高优先级 } // 筛选要添加属性的事件 - (BOOL)isMatchedWithFilter:(id)filter { // 只为 track 类型事件添加属性 return filter.type == SAEventTypeTrack; } // 返回要添加的属性 - (NSDictionary *)properties { return @{ @"plugin_name": @"MyPropertyPlugin", @"session_id": [[NSUUID UUID] UUIDString] }; } @end // 注册属性插件 MyPropertyPlugin *plugin = [[MyPropertyPlugin alloc] init]; [[SensorsAnalyticsSDK sharedInstance] registerPropertyPlugin:plugin]; // 注销属性插件 [[SensorsAnalyticsSDK sharedInstance] unregisterPropertyPluginWithPluginClass:[MyPropertyPlugin class]]; ``` -------------------------------- ### Bind Business Identities Source: https://context7.com/sensorsdata/sa-sdk-ios/llms.txt Associate multiple business IDs with a user for cross-platform tracking. ```objectivec // 绑定手机号 [[SensorsAnalyticsSDK sharedInstance] bind:SensorsAnalyticsIdentityKeyMobile value:@"13800138000"]; // 绑定邮箱 [[SensorsAnalyticsSDK sharedInstance] bind:SensorsAnalyticsIdentityKeyEmail value:@"user@example.com"]; // 绑定自定义业务 ID [[SensorsAnalyticsSDK sharedInstance] bind:@"wechat_openid" value:@"wx_oABC123456"]; // 获取已绑定的所有业务 ID NSDictionary *identities = [[SensorsAnalyticsSDK sharedInstance] identities]; NSLog(@"已绑定的业务 ID: %@", identities); // 解绑手机号 [[SensorsAnalyticsSDK sharedInstance] unbind:SensorsAnalyticsIdentityKeyMobile value:@"13800138000"]; // 重置匿名 ID [[SensorsAnalyticsSDK sharedInstance] resetAnonymousId]; [[SensorsAnalyticsSDK sharedInstance] resetAnonymousIdentity:@"custom_anonymous_id"]; ``` -------------------------------- ### URL Scheme Handling Source: https://context7.com/sensorsdata/sa-sdk-ios/llms.txt Handle scenarios where the app is opened via a URL Scheme, supporting features like scan-to-debug and DeepLink. This is crucial for external app interactions. ```APIDOC ## URL Scheme Handling Handle scenarios where the app is opened via a URL Scheme, supporting features like scan-to-debug and DeepLink. ### Method - `canHandleURL:`: Checks if the SDK can handle the given URL. - `handleSchemeUrl:`: Processes the URL to extract relevant data for the SDK. ### Code Examples ```objectivec // Handle URL in AppDelegate - (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary *)options { // Check if the SensorsData SDK can handle the URL if ([[SensorsAnalyticsSDK sharedInstance] canHandleURL:url]) { [[SensorsAnalyticsSDK sharedInstance] handleSchemeUrl:url]; return YES; } // Handle other business URLs return NO; } // Handle Universal Link - (BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void (^)(NSArray> *))restorationHandler { if ([[SensorsAnalyticsSDK sharedInstance] canHandleURL:userActivity.webpageURL]) { [[SensorsAnalyticsSDK sharedInstance] handleSchemeUrl:userActivity.webpageURL]; } return YES; } ``` ``` -------------------------------- ### User Profile Settings (Profile) Source: https://context7.com/sensorsdata/sa-sdk-ios/llms.txt Set user properties, supporting overwrite, first-time set, numeric increment, and list append operations. ```APIDOC ## User Profile Settings (Profile) ### Description Set user properties, supporting overwrite, first-time set, numeric increment, and list append operations. ### Methods - **set:** Sets user properties. Overwrites existing properties. - **set:to:** Sets a single user property. - **setOnce:** Sets a user property only if it doesn't exist. Useful for immutable properties like registration time. - **increment:** Increments a numeric user property. Useful for properties like points or visit counts. - **append:** Appends elements to a list-based user property. - **unset:** Deletes a specific user property. - **deleteUser:** Deletes all properties associated with the current user. ### Request Examples ```objectivec // set: Overwrite existing properties [[SensorsAnalyticsSDK sharedInstance] set:@{ @"nickname": @"张三", @"gender": @"男", @"age": @28, @"vip_level": @"黄金会员" }]; // set:to: Set a single property [[SensorsAnalyticsSDK sharedInstance] set:@"email" to:@"zhangsan@example.com"]; // setOnce: Set only if not already set [[SensorsAnalyticsSDK sharedInstance] setOnce:@{ @"first_visit_time": [NSDate date], @"register_source": @"官网活动" }]; // increment: Numeric property increment [[SensorsAnalyticsSDK sharedInstance] increment:@"points" by:@100]; [[SensorsAnalyticsSDK sharedInstance] increment:@{ @"login_count": @1, @"total_spent": @299.00 }]; // append: Append to a list property [[SensorsAnalyticsSDK sharedInstance] append:@"favorite_categories" by:[NSSet setWithObjects:@"数码", @"家电", nil]]; // unset: Delete a property [[SensorsAnalyticsSDK sharedInstance] unset:@"temp_tag"]; // deleteUser: Delete all user properties [[SensorsAnalyticsSDK sharedInstance] deleteUser]; ``` ``` -------------------------------- ### Track Custom Events Source: https://context7.com/sensorsdata/sa-sdk-ios/llms.txt Use the track method to record user actions. Properties can include various data types such as strings, numbers, arrays, and dates. ```objectivec // 基础事件追踪 [[SensorsAnalyticsSDK sharedInstance] track:@"ViewProduct"]; // 带属性的事件追踪 [[SensorsAnalyticsSDK sharedInstance] track:@"AddToCart" withProperties:@{ @"product_id": @"SKU12345", @"product_name": @"iPhone 15 Pro", @"product_price": @7999.00, @"product_category": @"手机数码", @"quantity": @1 }]; // 购买事件示例 NSDictionary *purchaseProperties = @{ @"order_id": @"ORDER_20231215_001", @"total_amount": @15998.00, @"payment_method": @"Apple Pay", @"items": @[@"SKU12345", @"SKU67890"], // 数组类型 @"coupon_used": @YES, @"purchase_time": [NSDate date] // 日期类型 }; [[SensorsAnalyticsSDK sharedInstance] track:@"Purchase" withProperties:purchaseProperties]; ``` -------------------------------- ### Data Sending Control (flush/deleteAll) Source: https://context7.com/sensorsdata/sa-sdk-ios/llms.txt Manually trigger data sending or clear local cached data. `flush` sends cached data immediately, bypassing interval and size limits. `deleteAll` removes all cached events and should be used with caution. ```APIDOC ## Data Sending Control (flush/deleteAll) Manually trigger data sending or clear local cached data. ### Method - `flush`: Immediately sends cached data, not limited by `flushInterval` and `flushBulkSize`. - `deleteAll`: Deletes all events in the local cache (use with caution!). - `setServerUrl`: Dynamically updates the server URL. - `serverUrl`: Gets the current server URL. ### Code Examples ```objectivec // Immediately send cached data (not limited by flushInterval and flushBulkSize) [[SensorsAnalyticsSDK sharedInstance] flush]; // Delete all events in the local cache (use with caution!) [[SensorsAnalyticsSDK sharedInstance] deleteAll]; // Dynamically update server URL [[SensorsAnalyticsSDK sharedInstance] setServerUrl:@"https://new-server.sensorsdata.cn/sa"]; // Get current server URL NSString *serverUrl = [[SensorsAnalyticsSDK sharedInstance] serverUrl]; NSLog(@"Current data receiving address: %@", serverUrl); ``` ``` -------------------------------- ### Manage User Profile Attributes Source: https://context7.com/sensorsdata/sa-sdk-ios/llms.txt Methods for setting, updating, incrementing, appending, and deleting user profile attributes. ```objectivec // set: 设置用户属性,已存在则覆盖 [[SensorsAnalyticsSDK sharedInstance] set:@{ @"nickname": @"张三", @"gender": @"男", @"age": @28, @"vip_level": @"黄金会员" }]; // set:to: 设置单个属性 [[SensorsAnalyticsSDK sharedInstance] set:@"email" to:@"zhangsan@example.com"]; // setOnce: 首次设置,已存在则忽略(适用于注册时间等不变属性) [[SensorsAnalyticsSDK sharedInstance] setOnce:@{ @"first_visit_time": [NSDate date], @"register_source": @"官网活动" }]; // increment: 数值累加(适用于积分、访问次数等) [[SensorsAnalyticsSDK sharedInstance] increment:@"points" by:@100]; [[SensorsAnalyticsSDK sharedInstance] increment:@{ @"login_count": @1, @"total_spent": @299.00 }]; // append: 向列表属性追加元素 [[SensorsAnalyticsSDK sharedInstance] append:@"favorite_categories" by:[NSSet setWithObjects:@"数码", @"家电", nil]]; // unset: 删除用户属性 [[SensorsAnalyticsSDK sharedInstance] unset:@"temp_tag"]; // deleteUser: 删除用户所有属性 [[SensorsAnalyticsSDK sharedInstance] deleteUser]; ``` -------------------------------- ### Enable JavaScript Bridge for H5 Integration Source: https://context7.com/sensorsdata/sa-sdk-ios/llms.txt Enable H5 and native app data communication by setting `enableJavaScriptBridge` to `YES` in `SAConfigOptions`. This allows H5 events to carry app-side user identifiers and properties. Manual tracking from H5 is also supported. ```objectivec // 在 SAConfigOptions 中开启 H5 打通 SAConfigOptions *options = [[SAConfigOptions alloc] initWithServerURL:serverURL launchOptions:launchOptions]; options.enableJavaScriptBridge = YES; // 开启 H5 打通 // 手动追踪 H5 事件(通常由 SDK 自动处理) NSString *eventInfo = @"{\"event\":\"H5Click\",\"properties\":{\"element\":\"button\"}}"; [[SensorsAnalyticsSDK sharedInstance] trackFromH5WithEvent:eventInfo]; // 带验证的 H5 事件追踪 [[SensorsAnalyticsSDK sharedInstance] trackFromH5WithEvent:eventInfo enableVerify:YES]; ``` -------------------------------- ### Manage User Login and Logout Source: https://context7.com/sensorsdata/sa-sdk-ios/llms.txt Associate an anonymous ID with a login ID using the login method. Use logout to clear the current user association. ```objectivec // 用户登录 - 基础用法 [[SensorsAnalyticsSDK sharedInstance] login:@"user_12345"]; // 用户登录 - 带属性,触发 $SignUp 事件并携带属性 [[SensorsAnalyticsSDK sharedInstance] login:@"user_12345" withProperties:@{ @"login_method": @"WeChat", @"is_new_user": @YES, @"register_channel": @"AppStore" }]; // 获取当前登录 ID NSString *loginId = [SensorsAnalyticsSDK sharedInstance].loginId; NSLog(@"当前登录用户: %@", loginId ?: @"未登录"); // 获取唯一标识(优先返回 loginId,无则返回 anonymousId) NSString *distinctId = [SensorsAnalyticsSDK sharedInstance].distinctId; // 用户登出 [[SensorsAnalyticsSDK sharedInstance] logout]; ``` -------------------------------- ### PropertyPlugin (Custom Properties) Source: https://context7.com/sensorsdata/sa-sdk-ios/llms.txt Customize property plugins to dynamically add properties when events are triggered. This allows for flexible and context-aware data enrichment. ```APIDOC ## PropertyPlugin (Custom Properties) Customize property plugins to dynamically add properties when events are triggered. ### Method - `priority`: Returns the priority of the plugin (e.g., `SAPropertyPluginPriorityHigh`). - `isMatchedWithFilter:`: Determines if the plugin should be applied to the current event based on filter criteria. - `properties`: Returns a dictionary of properties to be added to the event. - `registerPropertyPlugin:`: Registers a custom property plugin with the SDK. - `unregisterPropertyPluginWithPluginClass:`: Unregisters a property plugin by its class. ### Code Examples ```objectivec // Create a custom property plugin @interface MyPropertyPlugin : SAPropertyPlugin @end @implementation MyPropertyPlugin // Set plugin priority - (SAPropertyPluginPriority)priority { return SAPropertyPluginPriorityHigh; // High priority } // Filter events to which properties should be added - (BOOL)isMatchedWithFilter:(id)filter { // Only add properties to track type events return filter.type == SAEventTypeTrack; } // Return properties to be added - (NSDictionary *)properties { return @{ @"plugin_name": @"MyPropertyPlugin", @"session_id": [[NSUUID UUID] UUIDString] }; } @end // Register property plugin MyPropertyPlugin *plugin = [[MyPropertyPlugin alloc] init]; [[SensorsAnalyticsSDK sharedInstance] registerPropertyPlugin:plugin]; // Unregister property plugin [[SensorsAnalyticsSDK sharedInstance] unregisterPropertyPluginWithPluginClass:[MyPropertyPlugin class]]; ``` ``` -------------------------------- ### ID-Mapping 3.0 Business ID Binding Source: https://context7.com/sensorsdata/sa-sdk-ios/llms.txt Supports binding and unbinding of multiple business IDs to achieve cross-platform user association. ```APIDOC ## ID-Mapping 3.0 Business ID Binding ### Description Supports binding and unbinding of multiple business IDs to achieve cross-platform user association. ### Methods - **bind:** Binds a business ID to the user. - **identities:** Retrieves all currently bound business IDs. - **unbind:** Unbinds a specific business ID. - **resetAnonymousId:** Resets the anonymous ID to a newly generated one. - **resetAnonymousIdentity:** Resets the anonymous ID to a custom value. ### Request Examples ```objectivec // Bind phone number [[SensorsAnalyticsSDK sharedInstance] bind:SensorsAnalyticsIdentityKeyMobile value:@"13800138000"]; // Bind email [[SensorsAnalyticsSDK sharedInstance] bind:SensorsAnalyticsIdentityKeyEmail value:@"user@example.com"]; // Bind custom business ID [[SensorsAnalyticsSDK sharedInstance] bind:@"wechat_openid" value:@"wx_oABC123456"]; // Get all bound business IDs NSDictionary *identities = [[SensorsAnalyticsSDK sharedInstance] identities]; NSLog(@"已绑定的业务 ID: %@", identities); // Unbind phone number [[SensorsAnalyticsSDK sharedInstance] unbind:SensorsAnalyticsIdentityKeyMobile value:@"13800138000"]; // Reset anonymous ID [[SensorsAnalyticsSDK sharedInstance] resetAnonymousId]; [[SensorsAnalyticsSDK sharedInstance] resetAnonymousIdentity:@"custom_anonymous_id"]; ``` ``` -------------------------------- ### Common Properties (SuperProperties) Source: https://context7.com/sensorsdata/sa-sdk-ios/llms.txt Set common properties that will be included with every event. Supports static and dynamic common properties. ```APIDOC ## Common Properties (SuperProperties) ### Description Set common properties that will be included with every event. Supports static and dynamic common properties. Priority: track properties > dynamic common properties > static common properties > auto-collected properties. ### Methods - **registerSuperProperties:** Registers static common properties. - **registerDynamicSuperProperties:** Registers dynamic common properties that are fetched when an event is triggered. - **currentSuperProperties:** Retrieves the current common properties. - **unregisterSuperProperty:** Removes a specific common property. - **clearSuperProperties:** Clears all common properties. ### Request Examples ```objectivec // Register static common properties [[SensorsAnalyticsSDK sharedInstance] registerSuperProperties:@{ @"app_version": @"2.5.0", @"platform": @"iOS", @"device_id": [UIDevice currentDevice].identifierForVendor.UUIDString }]; // Register dynamic common properties (fetched dynamically) [[SensorsAnalyticsAnalyticsSDK sharedInstance] registerDynamicSuperProperties:^NSDictionary * _Nonnull{ // Get current network status, App status, etc. __block UIApplicationState appState; if ([NSThread isMainThread]) { appState = [UIApplication sharedApplication].applicationState; } else { dispatch_sync(dispatch_get_main_queue(), ^{ appState = [UIApplication sharedApplication].applicationState; }); } return @{ @"app_state": appState == UIApplicationStateActive ? @"前台" : @"后台", @"current_time": @([[NSDate date] timeIntervalSince1970]) }; }]; // Get current common properties NSDictionary *superProps = [[SensorsAnalyticsSDK sharedInstance] currentSuperProperties]; NSLog(@"当前公共属性: %@", superProps); // Unregister a specific common property [[SensorsAnalyticsSDK sharedInstance] unregisterSuperProperty:@"temp_property"]; // Clear all common properties [[SensorsAnalyticsSDK sharedInstance] clearSuperProperties]; ``` ``` -------------------------------- ### H5 Integration (JavaScriptBridge) Source: https://context7.com/sensorsdata/sa-sdk-ios/llms.txt Enable data communication between H5 pages and the native app, allowing H5 events to carry app-side user identifiers and properties. This bridges the gap between web and native experiences. ```APIDOC ## H5 Integration (JavaScriptBridge) Enable data communication between H5 pages and the native app, allowing H5 events to carry app-side user identifiers and properties. ### Method - `enableJavaScriptBridge`: Enable JavaScript Bridge in `SAConfigOptions`. - `trackFromH5WithEvent:`: Manually track H5 events (usually handled automatically by the SDK). - `trackFromH5WithEvent:enableVerify:`: Track H5 events with verification. ### Code Examples ```objectivec // Enable H5 integration in SAConfigOptions SAConfigOptions *options = [[SAConfigOptions alloc] initWithServerURL:serverURL launchOptions:launchOptions]; options.enableJavaScriptBridge = YES; // Enable H5 integration // Manually track H5 event (usually handled automatically by the SDK) NSString *eventInfo = @"{\"event\":\"H5Click\",\"properties\":{\"element\":\"button\"}}"; [[SensorsAnalyticsSDK sharedInstance] trackFromH5WithEvent:eventInfo]; // Track H5 event with verification [[SensorsAnalyticsSDK sharedInstance] trackFromH5WithEvent:eventInfo enableVerify:YES]; ``` ``` -------------------------------- ### SDK State Control Source: https://context7.com/sensorsdata/sa-sdk-ios/llms.txt Control the SDK's enabled/disabled state and log output. This allows for managing data collection and debugging. ```APIDOC ## SDK State Control Control the SDK's enabled/disabled state and log output. ### Method - `disableSDK`: Disables the SDK, stopping data collection and sending. - `enableSDK`: Enables the SDK, resuming data collection. - `enableLog:`: Toggles SDK logging (YES to enable, NO to disable). - `libVersion`: Gets the current SDK version. - `getPresetProperties`: Retrieves the SDK's preset properties. - `clearKeychainData`: Clears Keychain data, including the distinct ID. ### Code Examples ```objectivec // Disable SDK (stop collecting and sending data) [SensorsAnalyticsSDK disableSDK]; // Enable SDK (resume data collection) [SensorsAnalyticsSDK enableSDK]; // Enable/disable logging [[SensorsAnalyticsSDK sharedInstance] enableLog:YES]; // Get SDK version NSString *version = [[SensorsAnalyticsSDK sharedInstance] libVersion]; NSLog(@"SDK Version: %@", version); // Get preset properties NSDictionary *presetProperties = [[SensorsAnalyticsSDK sharedInstance] getPresetProperties]; NSLog(@"Preset Properties: %@", presetProperties); // Clear Keychain data (including distinct_id) [[SensorsAnalyticsSDK sharedInstance] clearKeychainData]; ``` ``` -------------------------------- ### Manage Anonymous IDs Source: https://context7.com/sensorsdata/sa-sdk-ios/llms.txt Retrieve, set, or reset anonymous identifiers for user tracking before login. ```objectivec // 获取当前匿名 ID NSString *anonymousId = [[SensorsAnalyticsSDK sharedInstance] anonymousId]; NSLog(@"当前匿名 ID: %@", anonymousId); // 自定义匿名 ID(建议在 SDK 初始化后立即调用) [[SensorsAnalyticsSDK sharedInstance] identify:@"custom_device_id_12345"]; // 重置匿名 ID(恢复为 SDK 自动生成的 ID) [[SensorsAnalyticsSDK sharedInstance] resetAnonymousId]; ``` -------------------------------- ### Event Timing (TrackTimer) Source: https://context7.com/sensorsdata/sa-sdk-ios/llms.txt Track the duration of events. Call `trackTimerStart` to begin and `trackTimerEnd` to end. The SDK automatically records the duration in the `event_duration` property (in seconds). ```APIDOC ## Event Timing (TrackTimer) ### Description Track the duration of events. Call `trackTimerStart` to begin and `trackTimerEnd` to end. The SDK automatically records the duration in the `event_duration` property (in seconds). ### Methods - **trackTimerStart:** Starts a timer for a given event. - **trackTimerPause:** Pauses an active timer. - **trackTimerResume:** Resumes a paused timer. - **trackTimerEnd:** Ends a timer and sends the event with `event_duration`. - **removeTimer:** Deletes a specific timer. - **clearTrackTimer:** Clears all active timers. ### Request Examples ```objectivec // Scenario: Track video playback duration // Start playback NSString *eventId = [[SensorsAnalyticsSDK sharedInstance] trackTimerStart:@"VideoPlay"]; NSLog(@"开始计时,eventId: %@", eventId); // ... User watches video ... // Pause playback (pause timer) [[SensorsAnalyticsSDK sharedInstance] trackTimerPause:@"VideoPlay"]; // Resume playback (resume timer) [[SensorsAnalyticsSDK sharedInstance] trackTimerResume:@"VideoPlay"]; // End playback (send event with event_duration) [[SensorsAnalyticsSDK sharedInstance] trackTimerEnd:@"VideoPlay" withProperties:@{ @"video_id": @"VID_12345", @"video_title": @"iOS 开发教程", @"play_type": @"完整播放" }]; // Cross-timing scenario (tracking multiple events with the same name simultaneously) NSString *timer1 = [[SensorsAnalyticsSDK sharedInstance] trackTimerStart:@"PageView"]; NSString *timer2 = [[SensorsAnalyticsSDK sharedInstance] trackTimerStart:@"PageView"]; // Differentiate between timers using eventId [[SensorsAnalyticsSDK sharedInstance] trackTimerEnd:timer1 withProperties:@{@"page": @"首页"}]; [[SensorsAnalyticsSDK sharedInstance] trackTimerEnd:timer2 withProperties:@{@"page": @"详情页"}]; // Remove a specific timer [[SensorsAnalyticsSDK sharedInstance] removeTimer:@"VideoPlay"]; // Clear all timers [[SensorsAnalyticsSDK sharedInstance] clearTrackTimer]; ``` ``` -------------------------------- ### Configure TrackEventCallback in Sensors Analytics SDK Source: https://context7.com/sensorsdata/sa-sdk-ios/llms.txt Use this callback during SDK initialization to filter sensitive events or inject custom properties into event payloads. ```objectivec // 方式一:通过 SAConfigOptions 配置(推荐) SAConfigOptions *options = [[SAConfigOptions alloc] initWithServerURL:serverURL launchOptions:launchOptions]; options.trackEventCallback = ^BOOL(NSString *eventName, NSMutableDictionary *properties) { // 过滤敏感事件 if ([eventName isEqualToString:@"SensitiveEvent"]) { return NO; // 返回 NO,丢弃该事件 } // 修改事件属性 properties[@"callback_timestamp"] = @([[NSDate date] timeIntervalSince1970]); // 移除敏感属性 [properties removeObjectForKey:@"password"]; return YES; // 返回 YES,事件入库 }; [SensorsAnalyticsSDK startWithConfigOptions:options]; ``` -------------------------------- ### Set and Delete Item Data Source: https://context7.com/sensorsdata/sa-sdk-ios/llms.txt Manage dimension table data like products or content. Use `itemSetWithType` to add or update item properties and `itemDeleteWithType` to remove items. ```objectivec // 设置 Item(商品信息) [[SensorsAnalyticsSDK sharedInstance] itemSetWithType:@"product" itemId:@"SKU12345" properties:@{ @"product_name": @"iPhone 15 Pro", @"brand": @"Apple", @"category": @"手机", @"price": @7999.00, @"stock": @100 }]; ``` ```objectivec // 设置 Item(文章信息) [[SensorsAnalyticsSDK sharedInstance] itemSetWithType:@"article" itemId:@"ART_001" properties:@{ @"title": @"iOS 数据采集最佳实践", @"author": @"技术团队", @"publish_date": [NSDate date] }]; ``` ```objectivec // 删除 Item [[SensorsAnalyticsSDK sharedInstance] itemDeleteWithType:@"product" itemId:@"SKU12345"]; ``` -------------------------------- ### Flush and Delete Cached Data Source: https://context7.com/sensorsdata/sa-sdk-ios/llms.txt Manually trigger data sending or clear local cache. Use `deleteAll` with caution as it permanently removes all cached events. ```objectivec // 立即发送缓存数据(不受 flushInterval 和 flushBulkSize 限制) [[SensorsAnalyticsSDK sharedInstance] flush]; ``` ```objectivec // 删除本地缓存的所有事件(慎用!) [[SensorsAnalyticsSDK sharedInstance] deleteAll]; ``` ```objectivec // 动态更新服务器地址 [[SensorsAnalyticsSDK sharedInstance] setServerUrl:@"https://new-server.sensorsdata.cn/sa"]; ``` ```objectivec // 获取当前服务器地址 NSString *serverUrl = [[SensorsAnalyticsSDK sharedInstance] serverUrl]; NSLog(@"当前数据接收地址: %@", serverUrl); ``` -------------------------------- ### Anonymous ID Management (identify) Source: https://context7.com/sensorsdata/sa-sdk-ios/llms.txt Customize the anonymous ID, suitable for scenarios where users need to be associated before login. ```APIDOC ## Anonymous ID Management (identify) ### Description Customize the anonymous ID, suitable for scenarios where users need to be associated before login. ### Methods - **anonymousId:** Retrieves the current anonymous ID. - **identify:** Sets a custom anonymous ID. Recommended to call immediately after SDK initialization. - **resetAnonymousId:** Resets the anonymous ID to the SDK-generated ID. ### Request Examples ```objectivec // Get current anonymous ID NSString *anonymousId = [[SensorsAnalyticsSDK sharedInstance] anonymousId]; NSLog(@"当前匿名 ID: %@", anonymousId); // Set custom anonymous ID (recommended after SDK initialization) [[SensorsAnalyticsSDK sharedInstance] identify:@"custom_device_id_12345"]; // Reset anonymous ID (restore to SDK-generated ID) [[SensorsAnalyticsSDK sharedInstance] resetAnonymousId]; ``` ``` -------------------------------- ### Item Operations Source: https://context7.com/sensorsdata/sa-sdk-ios/llms.txt Set and delete Item data, applicable to dimension tables such as products and content. Items represent entities with properties that can be tracked. ```APIDOC ## Item Operations Set and delete Item data, applicable to dimension tables such as products and content. ### Method - `itemSetWithType:itemId:properties:`: Sets or updates an item with its type, ID, and properties. - `itemDeleteWithType:itemId:`: Deletes an item by its type and ID. ### Code Examples ```objectivec // Set Item (product information) [[SensorsAnalyticsSDK sharedInstance] itemSetWithType:@"product" itemId:@"SKU12345" properties:@{ @"product_name": @"iPhone 15 Pro", @"brand": @"Apple", @"category": @"手机", @"price": @7999.00, @"stock": @100 }]; // Set Item (article information) [[SensorsAnalyticsSDK sharedInstance] itemSetWithType:@"article" itemId:@"ART_001" properties:@{ @"title": @"iOS Data Collection Best Practices", @"author": @"Technical Team", @"publish_date": [NSDate date] }]; // Delete Item [[SensorsAnalyticsSDK sharedInstance] itemDeleteWithType:@"product" itemId:@"SKU12345"]; ``` ``` -------------------------------- ### Push ID Management Source: https://context7.com/sensorsdata/sa-sdk-ios/llms.txt Set and delete user properties related to push notifications for integration with push services. This allows for targeted push campaigns. ```APIDOC ## Push ID Management Set and delete push-related user properties for push service integration. ### Method - `profilePushKey:pushId:`: Sets a push ID for a given key (e.g., 'jgId' for JPush, 'getui_id' for Getui, 'apns_token' for APNs). - `profileUnsetPushKey:`: Deletes a push ID associated with a specific key. ### Code Examples ```objectivec // Set JPush ID [[SensorsAnalyticsSDK sharedInstance] profilePushKey:@"jgId" pushId:@"JPush_Device_ID"]; // Set Getui ID [[SensorsAnalyticsSDK sharedInstance] profilePushKey:@"getui_id" pushId:@"Getui_Device_ID"]; // Set APNs Token NSString *deviceToken = @""; [[SensorsAnalyticsSDK sharedInstance] profilePushKey:@"apns_token" pushId:deviceToken]; // Delete push ID [[SensorsAnalyticsSDK sharedInstance] profileUnsetPushKey:@"jgId"]; ``` ``` -------------------------------- ### Manage Push Notification IDs Source: https://context7.com/sensorsdata/sa-sdk-ios/llms.txt Set and unset push-related user profile properties for integrating with push notification services. Supports various push providers like JPush, Getui, and APNs. ```objectivec // 设置极光推送 ID [[SensorsAnalyticsSDK sharedInstance] profilePushKey:@"jgId" pushId:@"极光推送ID"]; ``` ```objectivec // 设置个推 ID [[SensorsAnalyticsSDK sharedInstance] profilePushKey:@"getui_id" pushId:@"个推推送ID"]; ``` ```objectivec // 设置 APNs Token NSString *deviceToken = @""; [[SensorsAnalyticsSDK sharedInstance] profilePushKey:@"apns_token" pushId:deviceToken]; ``` ```objectivec // 删除推送 ID [[SensorsAnalyticsSDK sharedInstance] profileUnsetPushKey:@"jgId"]; ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.