Skip to content

SDK Initialization

This document covers iOS/tvOS/macOS SDK initialization and runtime capabilities.

Basic Configuration

On iOS/tvOS, initialization is typically performed in AppDelegate. On macOS, the viewDidLoad method of the first displayed NSViewController and the windowDidLoad method of NSWindowController are called earlier than AppDelegate's applicationDidFinishLaunching. To avoid lifecycle collection anomalies for the first view, initialize the SDK in main.m or main.swift.

-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
    // SDK FTSDKConfig settings
     // 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 <GuanceSDK/GuanceSDK.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 settings
       // 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 GuanceSDK
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, new code should use FTSDKConfig. FTMobileConfig is still compatible and inherits from FTSDKConfig; for versions earlier than 1.6.6, continue using FTMobileConfig.

Attribute Type Required Description
datakitUrl NSString Yes Reporting URL for local environment deployment (DataKit), for example: http://10.0.0.1:9529. The default port is 9529. Devices with the SDK installed must be able to access this address. Note: Configure either datakitUrl or datawayUrl, not both.
datawayUrl NSString Yes Public DataWay reporting URL, obtained from the [Real User Monitoring (RUM)] application. Example: https://open.dataway.url. Devices with the SDK installed must be able to access this address. Note: Configure either datakitUrl or datawayUrl, not both.
clientToken NSString Yes Authentication token, which 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. Custom values are supported. You can also set it using the -setEnvWithType: method with the provided FTEnv enumeration.
service NSString No Sets the name of the business or service to which it belongs. 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. For addition rules, see here.
groupIdentifiers NSArray No An array of AppGroups Identifiers corresponding to the iOS Widget Extensions to collect. If Widget Extensions data collection is enabled, you must set App Groups and configure the Identifier in this property. macOS does not support Widget Extension.
autoSync BOOL No Whether to automatically sync data to the server after collection. Default: YES. When set to NO, use [[FTMobileAgent sharedInstance] flushSyncData] on iOS/tvOS and [[FTSDKAgent sharedInstance] flushSyncData] on macOS to manage data synchronization yourself.
syncPageSize int No Sets the number of entries per sync request. Range: [5,). Note: The larger the number of request entries, the more computing resources data synchronization consumes. Default: 10.
syncSleepTime int No Sets the sync interval. Range: [0,5000]. Not set by default.
enableDataIntegerCompatible BOOL No Recommended when data needs to coexist with web data. This configuration handles web data type storage compatibility issues.
compressIntakeRequests BOOL No Applies deflate compression to uploaded sync data. This parameter is supported in SDK 1.5.6 and later and is disabled by default.
enableLimitWithDbSize BOOL No Enables the feature that limits the total cache size using the DB. Note: After this is enabled, FTLoggerConfig.logCacheLimitCount and FTRUMConfig.rumCacheLimitCount no longer take effect. This parameter is supported in SDK 1.5.8 and later.
dbCacheLimit long No DB cache size limit. Range: [30MB,). Default: 100MB, in bytes. This parameter is supported in SDK 1.5.8 and later.
dbDiscardType FTDBCacheDiscard No Sets the data discard rule in the database. Default: FTDBDiscard. FTDBDiscard discards appended data when the number of data records exceeds the maximum value; FTDBDiscardOldest discards old data when the data exceeds the maximum value. This parameter is supported in SDK 1.5.8 and later.
dataModifier FTDataModifier No Modifies a single field. Supported in SDK 1.5.16 and later. For usage examples, see Data Collection Masking.
lineDataModifier FTLineDataModifier No Modifies a single data record. Supported in SDK 1.5.16 and later. For usage examples, see Data Collection Masking.
enableDataFilter BOOL No Whether to enable SDK-side blocklist filtering. Default: YES. Supports filtering Log and RUM data. Supported in SDK 1.6.4 and later. For usage examples, see Blocklist Filtering.
dataFilters NSDictionary No Configures in-app blocklist rules. Supports two data categories: logging and rum. Supported in SDK 1.6.4 and later. For rule syntax, see Blocklist Rules.
allowWebViewHost NSArray<NSString *> No SDK 1.6.8+: Unified host allowlist for automatic WebView Bridge, which also controls RUM, Log, and Visitor ID access. nil allows all; an empty array blocks all. Configure this before SDK initialization. For rules and priority, see WebView Data Monitoring.
remoteConfiguration BOOL No Whether to enable remote configuration. Disabled by default. It must be set before SDK initialization, and a valid reporting URL and RUM App ID must be configured; updates are attempted at the minimum interval when RUM is initialized or the app returns to the foreground. Supported in SDK 1.5.17 and later, with DataKit >= 1.60 or public Dataway. For details, see Remote Configuration.
remoteConfigMiniUpdateInterval int No Minimum update interval for remote configuration, in seconds. Default: 12 hours. This value limits the request frequency and is not a scheduled refresh period. Supported in SDK 1.5.17 and later.
remoteConfigFetchCompletionBlock FTRemoteConfigFetchCompletionBlock No Registers a global callback before SDK initialization to receive fetch results and customize configuration through the returned model. For manual updates, you can pass a callback for this update to override the global callback. See Initialization and Manual Update Examples. Supported in SDK 1.5.19 and later.

Blocklist 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 with FTSDKConfig.enableDataFilter = NO.

Blocklist rules can be configured centrally in the blocklist of the Guance workspace and automatically pulled by the SDK from DataKit or DataWay; they can also be configured in the app through FTSDKConfig.dataFilters. Both methods correspond to the same blocklist filtering capability and can be used together. If any rule matches, that data record is discarded.

Blocklist filtering is performed after lineDataModifier and before writing to the local cache. If both lineDataModifier and blocklist filtering are configured, filtering rules evaluate the modified data.

enableDataFilter only controls rule pulling and filtering on the SDK side. When set to NO, the SDK no longer applies dataFilters or pulls workspace rules; when reporting through DataKit, the workspace blocklist 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, so 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 immediately pulls workspace blocklist rules during initialization. Subsequent pull intervals are based on the pull_interval returned by the server; if the server does not return a valid value, the SDK uses 10 seconds as a fallback interval. pull_interval supports seconds or strings with units, such as 10, 30s, 2m, and 1h.

Rule Syntax

The Data Filter rule syntax is basically the same as that of blocklist filtering rules. For complete syntax, see Blocklist Filtering Rules.

The key in dataFilters represents the data category. Currently, the SDK supports:

Category Description
logging Log data
rum RUM data

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

For field value formats and operator semantics, see Field Value Format Description and Operator Description in the blocklist filtering rules.

Use the array format for field values in SDK rule strings. Negated operators support not in and not match, and are also compatible with notin, notmatch, and not_in used in server-delivered rules.

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

User Binding and Unbinding

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

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

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

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

For precautions on adding extra, see here.

Runtime Capabilities

Shut Down the SDK

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

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

Clear SDK Cache Data

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

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

Manually Sync Data

Use FTMobileAgent to manually sync data.

You only need to perform data synchronization yourself when FTSDKConfig.autoSync = NO. The legacy FTMobileConfig.autoSync is still compatible.

- (void)flushSyncData;
func flushSyncData()

Manually Sync Dynamic Configuration

Capabilities related to dynamic configuration have been split into Dynamic Configuration.

Feedback

Is this page helpful?