Skip to content

SDK Initialization

This article covers the initialization and runtime capabilities of the iOS/tvOS/macOS SDK.

Basic Configuration

For iOS/tvOS, initialization is usually performed in AppDelegate. On macOS, the viewDidLoad method of the first displayed NSViewController and the windowDidLoad method of NSWindowController are called before AppDelegate's applicationDidFinishLaunching. To avoid abnormal lifecycle collection for the first view, it is recommended to initialize the SDK in main.m or main.swift.

-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
    // SDK FTSDKConfig configuration
     // Local environment deployment, Datakit deployment
     //FTSDKConfig *config = [[FTSDKConfig alloc]initWithDatakitUrl:datakitUrl];
     // Use public DataWay deployment
    FTSDKConfig *config = [[FTSDKConfig alloc]initWithDatawayUrl:datawayUrl clientToken:clientToken];
    //config.enableSDKDebugLog = YES;              //Debug mode
    config.compressIntakeRequests = YES;
    // Start the SDK
    [FTMobileAgent startWithConfigOptions:config];

   //...
    return YES;
}
// main.m file
#import <Cocoa/Cocoa.h>
#import <TrueWatchSDK/TrueWatchSDK.h>
int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // Local environment deployment, Datakit deployment
        FTSDKConfig *config = [[FTSDKConfig alloc] initWithDatakitUrl:datakitUrl];
        // Use public DataWay deployment
        // FTSDKConfig *config = [[FTSDKConfig alloc] initWithDatawayUrl:datawayUrl clientToken:clientToken];
        config.enableSDKDebugLog = YES;
        [FTSDKAgent startWithConfigOptions:config];
    }
    return NSApplicationMain(argc, argv);
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
     // SDK FTSDKConfig configuration
       // Local environment deployment, Datakit deployment
       //let config = FTSDKConfig(datakitUrl: url)
       // Use public DataWay deployment
     let config = FTSDKConfig(datawayUrl: datawayUrl, clientToken: clientToken)
     //config.enableSDKDebugLog = true              //Debug mode
     config.compressIntakeRequests = true           //Compress reported data
     FTMobileAgent.start(withConfigOptions: config)
     //...
     return true
}

Create a main.swift file and remove @main or @NSApplicationMain from AppDelegate.swift.

import Cocoa
import TrueWatchSDK
let delegate = AppDelegate()
NSApplication.shared.delegate = delegate

let config = FTSDKConfig(datakitUrl: datakitUrl)
// Use public DataWay deployment
// let config = FTSDKConfig(datawayUrl: datawayUrl, clientToken: clientToken)
config.enableSDKDebugLog = true
FTSDKAgent.start(withConfigOptions: config)

_ = NSApplicationMain(CommandLine.argc, CommandLine.unsafeArgv)
Initialization Configuration Naming

In SDK 1.6.6 and later, it is recommended that new code use FTSDKConfig. FTMobileConfig is still compatible and inherits from FTSDKConfig. For versions below 1.6.6, continue using FTMobileConfig.

Property Type Required Description
datakitUrl NSString Yes URL address for reporting to a local environment deployment (Datakit), for example: http://10.0.0.1:9529, default port 9529. The device with the SDK installed must be able to access this address. Note: configure either datakitUrl or datawayUrl, not both
datawayUrl NSString Yes URL address for reporting to the public DataWay, obtained from the [Real User Monitoring (RUM)] app, for example: https://open.dataway.url. The device with the SDK installed must be able to access this address. Note: configure either datakitUrl or datawayUrl, not both
clientToken NSString Yes Authentication token, must be used together with datawayUrl
enableSDKDebugLog BOOL No Sets whether to allow log printing. Default: NO
env NSString No Sets the collection environment. Default: prod. Supports customization, and can also be set using the provided FTEnv enum via the -setEnvWithType: method
service NSString No Sets the name of the business or service it belongs to. Affects the service field data in Log and RUM. Defaults: df_rum_ios for iOS, df_rum_tvos for tvOS, and df_rum_macos for macOS
globalContext NSDictionary No Adds custom tags. See here for the adding rules
groupIdentifiers NSArray No Array of App Groups Identifiers corresponding to the iOS Widget Extensions to be collected. If Widget Extensions data collection is enabled, you must set App Groups and configure the Identifier in this property. macOS does not support Widget Extensions
autoSync BOOL No Whether to automatically sync data to the server after collection. Default: YES. When set to NO, manage data sync manually using [[FTMobileAgent sharedInstance] flushSyncData] on iOS/tvOS and [[FTSDKAgent sharedInstance] flushSyncData] on macOS
syncPageSize int No Sets the number of entries per sync request. Range: [5,). Note: the larger the number of entries per request, the more computing resources data sync consumes. Default: 10
syncSleepTime int No Sets the sync interval. Range: [0,5000], not set by default
enableDataIntegerCompatible BOOL No It is recommended to enable this when data needs to coexist with web data. This configuration is used to handle storage compatibility issues for web data types
compressIntakeRequests BOOL No Applies deflate compression to uploaded sync data. Supported in SDK 1.5.6 and later. Disabled by default
enableLimitWithDbSize BOOL No Enables using the DB to limit the total cache size. Note: After enabling this, FTLoggerConfig.logCacheLimitCount and FTRUMConfig.rumCacheLimitCount will no longer take effect. Supported in SDK 1.5.8 and later
dbCacheLimit long No DB cache size limit. Range: [30MB,), default 100MB, in bytes. Supported in SDK 1.5.8 and later
dbDiscardType FTDBCacheDiscard No Sets the data discard rule in the database. Default: FTDBDiscard. FTDBDiscard discards newly appended data when the data count exceeds the maximum; FTDBDiscardOldest discards old data when the data count exceeds the maximum. Supported in SDK 1.5.8 and later
dataModifier FTDataModifier No Modifies individual fields. Supported in SDK 1.5.16 and later. See Data Collection Masking for usage examples
lineDataModifier FTLineDataModifier No Modifies a single data entry. Supported in SDK 1.5.16 and later. See Data Collection Masking for usage examples
enableDataFilter BOOL No Whether to enable SDK-side blacklist filtering. Default: YES. Supports filtering Log and RUM data. Supported in SDK 1.6.4 and later. See Blacklist Filtering for usage examples
dataFilters NSDictionary No Configures in-app blacklist rules, supporting logging and rum data. Supported in SDK 1.6.4 and later. See Blacklist Rules for the rule syntax
remoteConfiguration BOOL No Whether to enable the remote configuration capability for data collection. Disabled by default. Once enabled, SDK initialization or a hot start of the app triggers a data update. Supported in SDK 1.5.17 and later. Datakit version >= 1.60 is required, or use a public DataWay
remoteConfigMiniUpdateInterval int No Sets the minimum update interval for remote dynamic configuration, in seconds. Default: 12 hours. Supported in SDK 1.5.17 and later
remoteConfigFetchCompletionBlock FTRemoteConfigFetchCompletionBlock No Callback for remote configuration results, used to receive the fetch results and support custom adjustments to the configuration model. Supported in SDK 1.5.19 and later. See here for usage examples

Blacklist Filtering

SDK 1.6.4 and later support filtering RUM and Log data before it is written to the local cache. This capability is enabled by default. You can disable SDK-side filtering by setting FTSDKConfig.enableDataFilter = NO.

Blacklist rules can be configured centrally in the Blacklist of the Guance workspace, and the SDK automatically pulls them from DataKit or DataWay. They can also be configured in-app via FTSDKConfig.dataFilters. Both methods correspond to the same blacklist filtering capability and can be used simultaneously; if any rule matches, the data entry is discarded.

Blacklist filtering runs after lineDataModifier and before writing to the local cache. If both lineDataModifier and blacklist filtering are configured, the filtering rules are evaluated against the modified data.

enableDataFilter only controls rule fetching and filtering on the SDK side. After setting it to NO, the SDK no longer applies dataFilters or pulls workspace rules. When reporting through DataKit, the workspace blacklist may still be enforced on the DataKit side.

Data Filter applies to the SDK data write path. Too many rules or overly complex regular expressions may affect data write performance. It is recommended to configure only necessary rules.

config.enableDataFilter = YES;
config.dataFilters = @{
    @"logging": @[@"{ source in [ 'df_rum_ios_log' ] and message match [ 'timeout' ] }"],
    @"rum": @[@"{ resource_status match [ '5..' ] }"]
};
config.enableDataFilter = true
config.dataFilters = [
    "logging": ["{ source in [ 'df_rum_ios_log' ] and message match [ 'timeout' ] }"],
    "rum": ["{ resource_status match [ '5..' ] }"]
]

The SDK pulls the workspace blacklist rules immediately at initialization. Subsequent pull intervals follow the pull_interval returned by the server; if the server does not return a valid value, the SDK uses 10 seconds as the fallback interval. pull_interval supports seconds or strings with units, for example 10, 30s, 2m, 1h.

Rule Syntax

The Data Filter rule syntax is basically the same as the blacklist filtering rules. For the complete syntax, refer to Blacklist Filtering Rules.

The key of dataFilters indicates the data category. The SDK currently supports:

Category Description
logging Log data
rum RUM data

Each rule is expressed as { condition }. If any rule matches, the data of that category is filtered. Rules can use the tag and field fields of the data, as well as the data type identifier fields source and measurement.

For field value formats and operator semantics, refer to Field Value Formats and Operators in the blacklist filtering rules.

In SDK rule strings, field values are recommended to be in array format. Reverse operators support not in and not match, and are also compatible with notin, notmatch, and not_in used in rules delivered by the server.

{ status in [ 'debug' ] and env not in [ 'prod' ] and message not match [ '.*error.*' ] }

Binding and Unbinding Users

Use FTMobileAgent to bind user information and unbind the current user.

/// Binds user information. Call this method after the user successfully logs in to bind user information.
///
/// - Parameters:
///   - Id: User ID
///   - userName: User name (optional)
///   - userEmail: User email (optional)
///   - extra: Additional user information (optional)
- (void)bindUserWithUserID:(NSString *)Id userName:(nullable NSString *)userName userEmail:(nullable NSString *)userEmail extra:(nullable NSDictionary *)extra;

/// Unbinds the current user. Call this method after the user logs out to unbind user information.
- (void)unbindUser;
/// Binds user information. Call this method after the user successfully logs in to bind user information.
///
/// - Parameters:
///   - Id: User ID
///   - userName: User name (optional)
///   - userEmail: User email (optional)
///   - extra: Additional user information (optional)
open func bindUser(withUserID Id: String, userName: String?, userEmail: String?, extra: [AnyHashable : Any]?)

/// Unbinds the current user. Call this method after the user logs out to unbind user information.
open func unbindUser()

For notes on the extra adding rules, see here.

Runtime Capabilities

Shutting Down the SDK

When shutting down the SDK with FTMobileAgent, be sure to call it on the main thread; otherwise, thread safety issues may occur. If you change the SDK configuration dynamically, shut down the SDK first to avoid generating incorrect data.

+ (void)shutDown;
open class func shutDown()

Clearing SDK Cached Data

Use FTMobileAgent to clear cached data that has not been reported.

+ (void)clearAllData;
open class func clearAllData()

Syncing Data Manually

Use FTMobileAgent to sync data manually.

You only need to sync data manually when FTSDKConfig.autoSync = NO. The older FTMobileConfig.autoSync remains compatible.

- (void)flushSyncData;
func flushSyncData()

Syncing Dynamic Configuration Manually

Dynamic configuration capabilities have been moved to Dynamic Configuration.