Menu

Basic API Introduction (macOS)

The following instructions apply to version v3.0.3 and above of SensorsAnalyticsSDK

User Association

User association is used to uniquely identify users and improve the accuracy of user behavior analysis. Currently, Sensors Analytics provides simple user association and global user association for different business scenarios.

Attention

Due to the modular architecture, the usage of user association in the macOS section can be referred to the iOS SDK. However, the usage of other interfaces needs to be based on this document.

User Property Settings

Retain Initial Properties

For properties that need to ensure that they are only effective when they are first set, such as the first recharge amount of a user, the first set nickname, etc., you can use the - setOnce: or - setOnce:to: interfaces to record. Different from the - set: method, if the user property being set already exists, this record will be ignored and will not overwrite the existing data. If the property does not exist, it will be automatically created:

Objective-C

// 设定用户 AdSource 渠道为为 "App Store" [[SensorsAnalyticsSDK sharedInstance] setOnce:@"AdSource" to:@"App Store"]; // 再次设定用户 AdSource 渠道,设定无效,AdSource 属性值仍然是 "App Store" [[SensorsAnalyticsSDK sharedInstance] setOnce:@"AdSource" to:@"Email"];

Swift

// 设定用户 AdSource 渠道为为 "App Store" SensorsAnalyticsSDK.sharedInstance()?.setOnce(["AdSource" : "App Store"]) // 再次设定用户 AdSource 渠道,设定无效,AdSource 属性值仍然是 "App Store" SensorsAnalyticsSDK.sharedInstance()?.setOnce(["AdSource" : "Email"])

Accumulate Numeric Properties

For some numerical properties, such as total consumption, user points, etc., we can use the - increment: or - increment:by: to accumulate the original value. Sensors Analytics will automatically calculate and save the accumulated value:

Objective-C

// 将用户游戏次数属性增加一次 // increment:by: 对一个属性进行累加 [[SensorsAnalyticsSDK sharedInstance] increment:@"GamePlayed" by:[NSNumber numberWithInt:1]]; // 增加用户付费次数和积分 // increment: 对一个或多个属性进行累加 [[SensorsAnalyticsSDK sharedInstance] increment:@{@"UserPaid" : [NSNumber numberWithInt:1], 												 @"PointEarned" : [NSNumber numberWithFloat:12.5]}];

Swift

// 将用户游戏次数属性增加一次 //increment:by: 对一个属性进行累加 SensorsAnalyticsSDK.sharedInstance()?.increment("GamePlayed", by: NSNumber.init(value: 1)) // 增加用户付费次数和积分 //increment: 对一个或多个属性进行累加 SensorsAnalyticsSDK.sharedInstance()?.increment(["UserPaid": NSNumber.init(value: 1), ])

Append List Properties

For list-type user properties, such as favorite movies, reviewed restaurants, etc., you can use the - append:by: interface to append new values:

Objective-C

// 设定用户观影列表属性,设定后属性 "Movies" 为: [@"Sicario", @"Love Letter"] [[SensorsAnalyticsSDK sharedInstance] append:@"Movies" by:[NSSet setWithArray:@[@"Sicario", @"Love Letter"]]];

Swift

// 设定用户观影列表属性,设定后属性 "Movies" 为: ["Sicario", "Love Letter"] SensorsAnalyticsSDK.sharedInstance()?.append("Movies", by: ["Sicario","Love Letter"] as (NSFastEnumeration & NSObjectProtocol))

The elements in the list-type attribute must be of type NSString. For the limitations of the list-type, please refer to Data Format.

Attribute Cancellation

If you need to cancel a set user attribute, you can call - unset: to cancel it:

Objective-C

// 取消设置 gender 属性 [[SensorsAnalyticsSDK sharedInstance] unset:@"Gender"];

Swift

// 取消设置 gender 属性 SensorsAnalyticsSDK.sharedInstance()?.unset("age")

Get User ID

Objective-C Simplified User Association

In Sensors Analytics, each event is associated with an ID, which is used to identify the user or device information associated with the event. We call it distinct_id, you can also get this ID through the distinctId API:

// 获取事件的 ID 标识 [[SensorsAnalyticsSDK sharedInstance] distinctId];

Swift Simplified User Association

In Sensors Analytics, each event is associated with an ID used to identify the user or device information associated with the event. We call it the distinct_id, and you can also obtain this ID through the - distinctId interface:

// 获取事件的 ID 标识 SensorsAnalyticsSDK.sharedInstance()?.distinctId

Objective-C Global User Association

SDK version needs to be >=4.3.0

Get the ID of the global user association

// 获取事件的 ID NSDictionary *SDKProperties = [[SensorsAnalyticsSDK sharedInstance] identities]; // 可以获取数据体中的 identities 对象:SDKProperties.identities

Swift Global User Association

SDK version needs to be >=4.3.0

Get the ID of the global user association

// 获取事件的 ID NSDictionary *SDKProperties = SensorsAnalyticsSDK.sharedInstance?.identities; // 可以获取数据体中的 identities 对象:SDKProperties.identities

By default, before the user logs in, distinct_id is an anonymous ID generated by the SDK based on the device, usually SerialNumber or UUID.

You can also get the current anonymous ID through the anonymousId API:

Objective-C

// 获取匿名 ID [[SensorsAnalyticsSDK sharedInstance] anonymousId];

Swift

// 获取匿名 ID SensorsAnalyticsSDK.sharedInstance()?.anonymousId()

Metric of Event Duration

v3.0.3+ versions SDK supports code tracking to measure the duration of events. You only need to call - trackTimerStart: at the beginning of an action, and call trackTimerEnd:withProperties: at the end of an action. The SDK will automatically calculate the duration in seconds and store it in the $event_duration property of the event:

Objective-C

// 开始播放视频时 [[SensorsAnalyticsSDK sharedInstance] trackTimerStart:@"WatchVideo"]; // 暂停播放时 [[SensorsAnalyticsSDK sharedInstance] trackTimerPause:@"WatchVideo"]; // 恢复播放时 [[SensorsAnalyticsSDK sharedInstance] trackTimerResume:@"WatchVideo"]; // 停止或者结束播放时 [[SensorsAnalyticsSDK sharedInstance] trackTimerEnd:@"WatchVideo" withProperties:@{@"VideoType": @"film"}];

Swift

SensorsAnalyticsSDK.sharedInstance()?.trackTimerStart("WatchVideo") SensorsAnalyticsSDK.sharedInstance()?.trackTimerPause("WatchVideo") SensorsAnalyticsSDK.sharedInstance()?.trackTimerResume("WatchVideo") SensorsAnalyticsSDK.sharedInstance()?.trackTimerEnd("WatchVideo", withProperties: ["VideoType" : "film"])

Duration statistics for overlapping events

By default, the duration statistics use the event name as the identifier, and the SDK automatically matches the start-end for events with the same name. If two events with the same name have overlapping periods, it will result in incorrect matching. To solve this problem, the Sensors Analytics SDK supports duration statistics for overlapping events. Developers need to save the return value of - trackTimerStart: in order to pause, resume, or stop the timer later:

Objective-C

// 开始第一个事件计时 NSString *timer1 = [[SensorsAnalyticsSDK sharedInstance] trackTimerStart:@"testTimer"]; // 开始第二个事件计时 NSString *timer2 = [[SensorsAnalyticsSDK sharedInstance] trackTimerStart:@"testTimer"]; //如果需要暂停第一个事件计时 [[SensorsAnalyticsSDK sharedInstance] trackTimerPause:timer1]; //如果需要恢复第一个事件计时 [[SensorsAnalyticsSDK sharedInstance] trackTimerResume:timer1]; // 结束第一个事件计时 [[SensorsAnalyticsSDK sharedInstance] trackTimerEnd:timer1]; // 结束第二个事件计时 [[SensorsAnalyticsSDK sharedInstance] trackTimerEnd:timer2];

Swift

// 开始第一个事件计时 eventTime1 = SensorsAnalyticsSDK.sharedInstance()?.trackTimerStart("testTimer") // 开始第二个事件计时 eventTime2 = SensorsAnalyticsSDK.sharedInstance()?.trackTimerStart("testTimer") //如果需要暂停第一个事件计时 SensorsAnalyticsSDK.sharedInstance()?.trackTimerPause(eventTime1) //如果需要恢复第一个事件计时 SensorsAnalyticsSDK.sharedInstance()?.trackTimerResume(eventTime1) // 结束第一个事件计时 SensorsAnalyticsSDK.sharedInstance()?.trackTimerEnd("eventTime1") // 结束第二个事件计时 SensorsAnalyticsSDK.sharedInstance()?.trackTimerEnd("eventTime2")
  • The event will not be recorded by the SDK until the trackTimerEnd: method is called.
  • When calling trackTimerStart: multiple times, only the last call will be used as the starting point for timing.
  • By default, the statistics do not include the time when the user's app is in the background.

Get preset properties

When recording events, the front-end SDK adds device-related preset properties to ensure the consistency between front-end and back-end event properties. In some cases, it may be necessary to retrieve the SDK's preset properties on the front-end and pass them to the server through the business interface. This can be achieved using the - getPresetProperties method and adding the retrieved properties to the event properties on the server side:

Objective-C

// 获取事件预置属性 [[SensorsAnalyticsSDK sharedInstance] getPresetProperties];

Swift

// 获取事件预置属性 SensorsAnalyticsSDK.sharedInstance()?.getPresetProperties()

Dynamic event properties

动态公共属性和公共属性的区别是:前者适合标记年龄,后者适合标记性别。

对于一些值会变化的公共属性,如当前游戏等级、最新金币余额等,v3.0.3+ 版本 SDK 提供了registerDynamicSuperProperties: 接口来设置动态公共属性:

Objective-C

[[SensorsAnalyticsSDK sharedInstance] registerDynamicSuperProperties:^NSDictionary<NSString *,id> * _Nonnull{ 	return @{@"level": <#当前游戏等级#>, 			 @"balance": <#最新金币余额#>}; }];

Swift

SensorsAnalyticsSDK.sharedInstance()?.registerDynamicSuperProperties({ () -> [String : Any] in return ["level": <#当前游戏等级#>, 			"balance", <#最新金币余额#>] })
  • The priority of event properties is: properties passed in when tracking events > dynamic global properties > global properties > preset properties
  • The constraints of dynamic global properties are the same as event properties, for details, please refer to Data format

Item Metadata Report

In the Sensot Tower recommender project, customers need to report item metadata to develop and maintain follow-up recommendation services. The macOS SDK provides methods to set and delete item metadata.

item_id (item ID) and item_type (item type) together compose a unique identifier for an item. All item-related methods must specify both the item ID and item type parameters to complete item operations.

Set Item Properties

To directly set an item, if it already exists, it will be overwritten. In addition to the item ID and item type, other item properties must be defined in the `properties` field. The constraints for item properties are the same as event properties, for detailed instructions, please refer to Data Format.

Objective-C

// 设置物品类型为 food 且物品 ID 为 2 的物品设置物品属性 @"name": @"玉米", @"flavour": @"甜" [[SensorsAnalyticsSDK sharedInstance] itemSetWithType:@"food" itemId:@"2" properties:@{@"name": @"玉米", @"flavour": @"甜"}];

Swift

// 设置物品类型为 food 且物品 ID 为 2 的物品设置物品属性 @"name": @"玉米", @"flavour": @"甜" SensorsAnalyticsSDK.sharedInstance()?.itemSetWithType:("food", itemId:"2", properties:["name": "玉米", "flavour": "甜"])

Delete Item Properties

If an item is no longer recommended and needs to be taken offline, it can be deleted. If it does not exist, it will be ignored. No other item properties are parsed except for the item ID and item type.

Objective-C

// 删除物品类型为 food 且物品 ID 为 2 的物品 [[SensorsAnalyticsSDK sharedInstance] itemDeleteWithType:@"food" itemId:@"2"];

Swift

// 删除物品类型为 food 且物品 ID 为 2 的物品 SensorsAnalyticsSDK.sharedInstance()?.itemDeleteWithType("food", itemId:"2")

Custom Report Strategy

To reduce performance and battery consumption, events triggered in macOS are not immediately reported to the server. Instead, the events are cached locally and then uploaded in batches at regular intervals.

Report Conditions

When an event is triggered, the macOS SDK checks the following conditions to determine whether to upload data to the server:
1. Whether the current network meets the flushNetworkPolicy (default is WiFi)
2. Whether the time interval since the last upload is greater than flushInterval (default is 15 seconds)
3. Whether the number of cached events is greater than flushBulkSize (default is 100)

SDK only sends data if condition 1 and 2 or condition 1 and 3 are met. The above parameters can be customized by modifying the corresponding parameter values to control the frequency of event reporting.

Objective-C

SAConfigOptions *options = [[SAConfigOptions alloc] initWithServerURL:@"<#数据接收地址#>" launchOptions:launchOptions]; // 设置触发间隔,默认 15 * 1000 毫秒 options.flushInterval = 10 * 1000; // 设置触发条数,默认 100 条 options.flushBulkSize = 50; [SensorsAnalyticsSDK startWithConfigOptions:options]; // 设置上报网络策略,默认 WiFi,注意需要初始化 SDK 之后设置 [[SensorsAnalyticsSDK sharedInstance] setFlushNetworkPolicy:SensorsAnalyticsNetworkTypeALL];

Swift

let options = SAConfigOptions.init(serverURL: "<#数据接收地址#>", launchOptions: launchOptions) // 设置触发间隔,默认 15 * 1000 毫秒 options.flushInterval = 10 * 1000 // 设置触发条数,默认 100 条 options.flushBulkSize = 50 SensorsAnalyticsSDK.start(configOptions: options) //设置上报网络策略,默认 3G、4G、5G、WiFi,注意需要初始化 SDK 之后设置 SensorsAnalyticsSDK.sharedInstance()?.setFlushNetworkPolicy(SensorsAnalyticsNetworkType.typeALL)

Force Reporting

If a specific event needs to be reported immediately, you can call the - flush interface to force reporting after the event is triggered:

Objective-C

// 立即上报 [[SensorsAnalyticsSDK sharedInstance] flush];

Swift

// 立即上报 SensorsAnalyticsSDK.sharedInstance()?.flush()

Cache Limit

If the conditions for reporting are not met after the event is triggered, the number of data cached locally will continue to increase. When the number of cached events reaches the maxCacheSize, the SDK will discard old data and keep the latest data each time a new event is triggered. The maxCacheSize is 10,000 by default and supports custom values:

Objective-C

// 设置最大缓存量,默认 10000 条 options.maxCacheSize = 20000;

Swift

// 设置最大缓存量,默认 10000 条 options.maxCacheSize = 20000

Clear Local Cached Events

To comply with GDPR requirements, version v3.0.3+ of the SDK has added the - deleteAll method to clear all locally cached events:

Objective-C

[[SensorsAnalyticsSDK sharedInstance] deleteAll];

Swift

SensorsAnalyticsSDK.sharedInstance()?.deleteAll()


Modify Event Information Before Storage

Starting from version v3.0.3+, the SDK supports modifying properties and deleting events before storage. You can use the - trackEventCallback: method to set the block parameter:

  1. The eventName parameter in the block represents the current event name.
  2. The properties parameter in the block represents the current event properties. This parameter is of type NSMutableDictionary and can be directly modified to modify the event properties.
  3. The return value in the block indicates whether the event needs to continue to be stored and reported: YES indicates the event will continue to be stored, NO indicates the event will be deleted.

warning

  • Do not call in block - track:- trackInstallation: - login:  The interface that triggers the event will cause the application to crash due to circular calls
  • When block return NO, the SDK will delete this event, so make sure to judge the logic so that you don't accidentally delete the event

Objective-C

[[SensorsAnalyticsSDK sharedInstance] trackEventCallback:^BOOL(NSString *eventName, NSMutableDictionary<NSString *,id> *properties) { // BuyProduct 事件不进行入库 if ([eventName isEqualToString:@"BuyProduct"]) { return NO; } // 删除 ViewProduct 事件 category 属性 if ([eventName isEqualToString:@"ViewProduct"]) { [properties removeObjectForKey:@"category"]; } return YES; }];

Swift

SensorsAnalyticsSDK.sharedInstance()?.trackEventCallback({ (eventName, properties) -> Bool in // BuyProduct 事件不进行入库 if (eventName == "BuyProduct"){ return false } // 删除 ViewProduct 事件 category 属性 if (eventName == "ViewProduct"){ properties.removeObject(forKey: "category") } return true })

custom anonymous ID

By default, the SDK generates an anonymous ID and can ensure that the ID is unique. If you need to replace the anonymous ID assigned by default, you can do so after initializing the SDKimmediatelycall identify: method to replace.
Code example:

Objective-C

[[SensorsAnalyticsSDK sharedInstance] identify:<#自定义匿名 ID#>];

Swift

SensorsAnalyticsSDK.sharedInstance()?.identify(<#自定义匿名 ID#>)
Previous
Integrated document(macOS)
Next
App Integration H5
Last modified: 2025-01-02