iOS/tvOS Application Integration¶
By collecting Metrics data from various iOS applications, visualize and analyze the performance of each iOS application.
Prerequisites¶
Note
If the RUM Headless service has been activated, the prerequisites are automatically configured, and the application can be directly integrated.
- Install DataKit;
- Configure the RUM Collector;
- Configure DataKit to be accessible over the public network and install the IP geolocation database.
Application Integration¶
- Go to User Access Monitoring > Create New Application > iOS;
- Enter the application name;
- Enter the application ID;
-
Select the application integration method:
- Public DataWay: Directly receives RUM data without installing the DataKit collector.
- Local Environment Deployment: Receives RUM data after meeting the prerequisites.
Installation¶
Source Code: https://github.com/GuanceCloud/datakit-ios
Demo: https://github.com/GuanceDemo/guance-app-demo
-
Configure the
Podfilefile.-
Use Dynamic Library
-
Use Static Library
-
Download the code repository locally for use
Podfilefile:use_modular_headers! # Main project target 'yourProjectName' do pod 'FTMobileSDK', :path => '[folder_path]' end # Widget Extension target 'yourWidgetExtensionName' do pod 'FTMobileSDK', :subspecs => ['Extension'] , :path => '[folder_path]' endfolder_path: The path to the folder containingFTMobileSDK.podspec.FTMobileSDK.podspecfile:Modify
s.versionands.sourcein theFTMobileSDK.podspecfile.Pod::Spec.new do |s| s.name = "FTMobileSDK" s.version = "[latest_version]" s.source = { :git => "https://github.com/GuanceCloud/datakit-ios.git", :tag => s.version } ends.version: Modify to the specified version, preferably consistent withSDK_VERSIONinFTMobileSDK/FTMobileAgent/Core/FTMobileAgentVersion.h.s.source:tag => s.version
-
-
Execute
pod installin thePodfiledirectory to install the SDK.
-
Configure the
Cartfilefile. -
Update dependencies.
Depending on your target platform (iOS or tvOS), execute the corresponding
carthage updatecommand and add the--use-xcframeworksparameter to generate XCFrameworks:-
For iOS platform:
-
For tvOS platform:
The generated xcframework is used in the same way as a regular Framework. Add the compiled library to the project.
FTMobileAgent: Add to the main project Target, supports iOS and tvOS platforms.FTMobileExtension: Add to the Widget Extension Target. -
-
Add
-ObjCtoTARGETS->Build Setting->Other Linker Flags. -
When using Carthage for integration, the SDK versions supported are:
FTMobileAgent: >=1.3.4-beta.2FTMobileExtension: >=1.4.0-beta.1
Using Xcode UI
-
Select
PROJECT->Package Dependency, click the + under thePackagessection. -
Enter
https://github.com/GuanceCloud/datakit-ios.gitin the search box on the pop-up page. -
After Xcode successfully fetches the package, it will display the SDK configuration page.
Dependency Rule: It is recommended to selectUp to Next Major Version.Add To Project: Select the supported project.After filling in the configuration, click the
Add Packagebutton and wait for the loading to complete. -
In the pop-up
Choose Package Products for datakit-ios, select the Target that needs to add the SDK, click theAdd Packagebutton, and the SDK will be successfully added.FTMobileSDK: Add to the main project TargetFTMobileExtension: Add to the Widget Extension Target
Using Package.swift
If your project is managed by SPM, add the SDK as a dependency by adding dependencies to Package.swift.
// Main project
dependencies: [
.package(url: "https://github.com/GuanceCloud/datakit-ios.git",
.upToNextMajor(from: "[latest_version]"))
]
Add dependencies for your Targets
targets: [
.target(
name: "YourTarget",
dependencies: [
.product(name: "FTMobileSDK", package: "FTMobileSDK"),
]),
.target(
name: "YourWidgetExtensionTarget",
dependencies: [
.product(name: "FTMobileExtension", package: "FTMobileSDK"),
]),
]
Note: 1.4.0-beta.1 and above support Swift Package Manager.
Add Header File¶
SDK Initialization¶
Basic Configuration¶
-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
// SDK FTMobileConfig settings
// Local environment deployment, Datakit deployment
//FTMobileConfig *config = [[FTMobileConfig alloc]initWithDatakitUrl:datakitUrl];
// Use public DataWay deployment
FTMobileConfig *config = [[FTMobileConfig alloc]initWithDatawayUrl:datawayUrl clientToken:clientToken];
//config.enableSDKDebugLog = YES; //debug mode
config.compressIntakeRequests = YES;
//Start SDK
[FTMobileAgent startWithConfigOptions:config];
//...
return YES;
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// SDK FTMobileConfig settings
// Local environment deployment, Datakit deployment
//let config = FTMobileConfig(datakitUrl: url)
// Use public DataWay deployment
let config = FTMobileConfig(datawayUrl: datawayUrl, clientToken: clientToken)
//config.enableSDKDebugLog = true //debug mode
config.compressIntakeRequests = true //Compress data upload
FTMobileAgent.start(withConfigOptions: config)
//...
return true
}
| Attribute | Type | Required | Meaning |
|---|---|---|---|
| datakitUrl | NSString | Yes | Local environment deployment (Datakit) upload URL address, example: http://10.0.0.1:9529, default port 9529, the device installing the SDK must be able to access this address. Note: Only one of datakitUrl and datawayUrl can be configured |
| datawayUrl | NSString | Yes | Public Dataway upload URL address, obtained from the [User Access Monitoring] application, example: https://open.dataway.url, the device installing the SDK must be able to access this address. Note: Only one of datakitUrl and datawayUrl can be configured |
| clientToken | NSString | Yes | Authentication token, must be used with datawayUrl |
| enableSDKDebugLog | BOOL | No | Set whether to allow log printing. Default NO |
| env | NSString | No | Set the collection environment. Default prod, supports customization, or can be set using the FTEnv enumeration through the -setEnvWithType: method |
| service | NSString | No | Set the name of the business or service. Affects the service field data in Log and RUM. Default: df_rum_ios |
| globalContext | NSDictionary | No | Add custom tags. Add rules refer to here |
| groupIdentifiers | NSArray | No | Array of AppGroups Identifiers corresponding to the Widget Extensions that need to be collected. If Widget Extensions data collection is enabled, App Groups must be set and the Identifier must be configured in this attribute |
| autoSync | BOOL | No | Whether to automatically synchronize data to the server after collection. Default YES. When NO, use [[FTMobileAgent sharedInstance] flushSyncData] to manage data synchronization manually |
| syncPageSize | int | No | Set the number of entries for synchronization requests. Range [5,)Note: The larger the number of request entries, the more computational resources the data synchronization occupies, default is 10 |
| syncSleepTime | int | No | Set the synchronization interval time. Range [0,5000], default is not set |
| enableDataIntegerCompatible | BOOL | No | It is recommended to enable this when coexisting with web data. This configuration is used to handle web data type storage compatibility issues. |
| compressIntakeRequests | BOOL | No | Compress the uploaded synchronization data with deflate, supported by SDK 1.5.6 and above, default is off |
| enableLimitWithDbSize | BOOL | No | Enable the use of DB to limit the total cache size. Note: After enabling, FTLoggerConfig.logCacheLimitCount and FTRUMConfig.rumCacheLimitCount will become invalid. Supported by SDK 1.5.8 and above |
| dbCacheLimit | long | No | DB cache limit size. Range [30MB,), default 100MB, unit byte, supported by SDK 1.5.8 and above |
| dbDiscardType | FTDBCacheDiscard | No | Set the data discard rule in the database. Default FTDBDiscard FTDBDiscard When the data count exceeds the maximum, discard the appended data. FTDBDiscardOldest When the data exceeds the maximum, discard the oldest data. Supported by SDK 1.5.8 and above |
| dataModifier | FTDataModifier | No | Modify individual fields. Supported by SDK 1.5.16 and above, usage example see here |
| lineDataModifier | FTLineDataModifier | No | Modify single data. Supported by SDK 1.5.16 and above, usage example see here |
| remoteConfiguration | BOOL | No | Whether to enable the remote configuration function for data collection, default is not enabled. After enabling, SDK initialization or application hot start will trigger data updates. Supported by SDK 1.5.17 and above. Datakit version requirement >=1.60 or use public dataway |
| remoteConfigMiniUpdateInterval | int | No | Set the minimum update interval for remote dynamic configuration, unit seconds, default 12 hours. Supported by SDK 1.5.17 and above |
RUM Configuration¶
//Enable rum
FTRumConfig *rumConfig = [[FTRumConfig alloc]initWithAppid:appid];
rumConfig.enableTraceUserView = YES;
rumConfig.deviceMetricsMonitorType = FTDeviceMetricsMonitorAll;
rumConfig.monitorFrequency = FTMonitorFrequencyRare;
rumConfig.enableTraceUserAction = YES;
rumConfig.enableTraceUserResource = YES;
rumConfig.enableTrackAppFreeze = YES;
rumConfig.enableTrackAppCrash = YES;
rumConfig.enableTrackAppANR = YES;
rumConfig.errorMonitorType = FTErrorMonitorAll;
[[FTMobileAgent sharedInstance] startRumWithConfigOptions:rumConfig];
let rumConfig = FTRumConfig(appid: appid)
rumConfig.enableTraceUserView = true
rumConfig.deviceMetricsMonitorType = .all
rumConfig.monitorFrequency = .rare
rumConfig.enableTraceUserAction = true
rumConfig.enableTraceUserResource = true
rumConfig.enableTrackAppFreeze = true
rumConfig.enableTrackAppCrash = true
rumConfig.enableTrackAppANR = true
rumConfig.errorMonitorType = .all
FTMobileAgent.sharedInstance().startRum(withConfigOptions: rumConfig)
| Attribute | Type | Required | Meaning |
|---|---|---|---|
| appid | NSString | Yes | The unique identifier for the User Access Monitoring application ID. Corresponds to setting the RUM appid, which enables the RUM collection function, method to obtain appid |
| samplerate | int | No | Sampling rate. Range [0,100], 0 means no collection, 100 means full collection, default is 100. Scope is all View, Action, LongTask, Error data under the same session_id |
| sessionOnErrorSampleRate | int | No | Set the error collection rate. When the session is not sampled by samplerate, if an error occurs during the session, data from the 1 minute before the error can be collected, range [0,100], 0 means no collection, 100 means full collection, default is 0. Scope is all View, Action, LongTask, Error data under the same session_id. Supported by SDK 1.5.16 and above |
| enableTrackAppCrash | BOOL | No | Set whether to collect crash logs. Default NO |
| enableTrackAppANR | BOOL | No | Collect ANR unresponsive events. DefaultNO |
| enableTrackAppFreeze | BOOL | No | Collect UI freeze events. DefaultNOCan be enabled and the freeze threshold can be set using the -setEnableTrackAppFreeze:freezeDurationMs: method |
| freezeDurationMs | long | No | Set the UI freeze threshold, range [100,), unit milliseconds, default 250ms. Supported by SDK 1.5.7 and above |
| enableTraceUserView | BOOL | No | Set whether to track user View operations. DefaultNO |
| enableTraceUserAction | BOOL | No | Set whether to track user Action operations. DefaultNO Can customize action_name using view.accessibilityIdentifier |
| enableTraceUserResource | BOOL | No | Set whether to track user network requests. DefaultNO, only works on native http Note: Network requests initiated through [NSURLSession sharedSession] cannot collect performance data;SDK 1.5.9 and above support collecting network requests initiated through Swift's URLSession async/await APIs. |
| resourceUrlHandler | FTResourceUrlHandler | No | Customize the collection rule for resource. Default is no filtering. Return: NO means to collect, YES means not to collect. |
| errorMonitorType | FTErrorMonitorType | No | Error event monitoring supplement type. Add monitoring information to the collected crash data. FTErrorMonitorBattery for battery level, FTErrorMonitorMemory for memory usage, FTErrorMonitorCpu for CPU occupancy, default is not set. |
| deviceMetricsMonitorType | FTDeviceMetricsMonitorType | No | View performance monitoring type, default is not set. Add corresponding monitoring item information to the collected View data. FTDeviceMetricsMonitorMemory monitors the current application memory usage, FTDeviceMetricsMonitorCpu monitors CPU ticks, FTDeviceMetricsMonitorFps monitors screen frame rate, default is not set. |
| monitorFrequency | FTMonitorFrequency | No | View performance monitoring sampling period. Configure monitorFrequency to set the sampling period for View monitoring item information. FTMonitorFrequencyDefault 500ms (default), FTMonitorFrequencyFrequent 100ms, FTMonitorFrequencyRare 1000ms. |
| enableResourceHostIP | BOOL | No | Whether to collect the IP address of the request target domain. Supported by >= iOS 13.0 >= tvOS 13.0 |
| globalContext | NSDictionary | No | Add custom tags, used to distinguish user monitoring data sources. If tracking function is needed, the parameter key is track_id, value is any value, add rule precautions refer to here |
| rumCacheLimitCount | int | No | RUM maximum cache limit. Default 100_000, supported by SDK 1.5.8 and above |
| rumDiscardType | FTRUMCacheDiscard | No | Set RUM discard rule. Default FTRUMCacheDiscard FTRUMCacheDiscard When RUM data count exceeds the maximum, discard appended data. FTRUMDiscardOldest When RUM data exceeds the maximum, discard the oldest data. Supported by SDK 1.5.8 and above |
| resourcePropertyProvider | FTResourcePropertyProvider | No | Add custom attributes to RUM Resource through block callback. Supported by SDK 1.5.10 and above. Priority lower than URLSession custom collection |
| enableTraceWebView | BOOL | No | Set to enable webView data collection, default YES. Supported by SDK 1.5.17 and above |
| allowWebViewHost | NSArray | No | Set the WebView host addresses allowed for data tracking, nil means full collection, default is nil. Supported by SDK 1.5.17 and above |
| sessionTaskErrorFilter | FTSessionTaskErrorFilter | No | Set whether to intercept URLSessionTask Error, confirm interception return YES, not intercept return NO, after interception RUM-Error will not collect this error. Supported by SDK 1.5.17 and above |
| viewTrackingHandler | FTViewTrackingHandler | No | Customize View tracking logic, used to determine which ViewControllers need to be monitored as RUM View and customize View Name. Effective condition: enableTraceUserView = YES. Supported by SDK 1.5.18 and above |
| actionTrackingHandler | FTActionTrackingHandler | No | Customize Action tracking logic, used to filter RUM Action events that need to be recorded and customize Action Name. Effective condition: enableTraceUserAction = YES. Supported by SDK 1.5.18 and above |
Log Configuration¶
//Enable logger
FTLoggerConfig *loggerConfig = [[FTLoggerConfig alloc]init];
loggerConfig.enableCustomLog = YES;
loggerConfig.enableLinkRumData = YES;
loggerConfig.logLevelFilter = @[@(FTStatusError),@(FTStatusCritical)];
loggerConfig.discardType = FTDiscardOldest;
[[FTMobileAgent sharedInstance] startLoggerWithConfigOptions:loggerConfig];
let loggerConfig = FTLoggerConfig()
loggerConfig.enableCustomLog = true
loggerConfig.enableLinkRumData = true
loggerConfig.logLevelFilter = [NSNumber(value: FTLogStatus.statusError.rawValue),NSNumber(value: FTLogStatus.statusCritical.rawValue)] // loggerConfig.logLevelFilter = [2,3]
loggerConfig.discardType = .discardOldest
FTMobileAgent.sharedInstance().startLogger(withConfigOptions: loggerConfig)
| Attribute | Type | Required | Meaning |
|---|---|---|---|
| samplerate | int | No | Sampling rate. Range [0,100], 0 means no collection, 100 means full collection, default is 100. |
| enableCustomLog | BOOL | No | Whether to upload custom log. DefaultNO |
| printCustomLogToConsole | BOOL | No | Set whether to output custom logs to the console. DefaultNO, custom logoutput format |
| logLevelFilter | NSArray | No | Set level log filtering, default is not set. Example: 1. Collect logs with levels Info and Error, set to @[@(FTStatusInfo),@(FTStatusError)] or @[@0,@1]2.Collect logs containing custom levels, such as collecting "customLevel" and Error, set to @[@"customLevel",@(FTStatusError)]Supported by SDK 1.5.16 and above for filtering custom levels |
| enableLinkRumData | BOOL | No | Whether to associate with RUM data. DefaultNO |
| globalContext | NSDictionary | No | Add log custom tags. Add rules refer to here |
| logCacheLimitCount | int | No | Local cache maximum log entry limit [1000,), the larger the log, the greater the disk cache pressure, default is 5000 |
| discardType | FTLogCacheDiscard | No | Set the log discard rule after reaching the limit. Default FTDiscard FTDiscard When the log data count exceeds the maximum (5000), discard appended data. FTDiscardOldest When the log data exceeds the maximum, discard the oldest data. |
Trace Configuration¶
| Attribute | Type | Required | Meaning |
|---|---|---|---|
| samplerate | int | No | Sampling rate. Range [0,100], 0 means no collection, 100 means full collection, default is 100. |
| networkTraceType | FTNetworkTraceType | No | Set the type of link tracing. Default is DDTrace, currently supports Zipkin, Jaeger, DDTrace, Skywalking (8.0+), TraceParent (W3C), if accessing OpenTelemetry, please refer to the supported types and agent related configurations when selecting the corresponding link type |
| enableLinkRumData | BOOL | No | Whether to associate with RUM data. DefaultNO |
| enableAutoTrace | BOOL | No | Set whether to enable automatic http trace. DefaultNO, currently only supports NSURLSession |
| traceInterceptor | FTTraceInterceptor | No | Supports custom link tracing by judging through URLRequest, confirm interception returns TraceContext, not intercept returns nil. Supported by SDK 1.5.10 and above. Priority lower than URLSession custom collection |
RUM User Data Tracking¶
FTRUMConfig configuration enableTraceUserAction, enableTraceUserView, enableTraceUserResource, enableTrackAppFreeze, enableTrackAppCrash and enableTrackAppANR to achieve automatic collection tracking of Action, View, Resource, LongTask, Error data. If you want to customize collection, you can use FTExternalDataManager to report data, as shown below:
View¶
Usage¶
/// Create page
///
/// Call before `-startViewWithName`, this method is used to record the page load time, if the load time cannot be obtained, this method can be omitted.
/// - Parameters:
/// - viewName: Page name
/// - loadTime: Page load time (nanoseconds)
-(void)onCreateView:(NSString *)viewName loadTime:(NSNumber *)loadTime;
/// Enter page
/// - Parameters:
/// - viewName: Page name
/// - property: Event custom attributes (optional)
-(void)startViewWithName:(NSString *)viewName property:(nullable NSDictionary *)property;
/// Update the current RUM View load time.
/// Must be called between `-startView` and `-stopView` to take effect.
/// - Parameter duration: Load duration (nanoseconds).
-(void)updateViewLoadingTime:(NSNumber *)duration;
/// Leave page
/// - Parameter property: Event custom attributes (optional)
-(void)stopViewWithProperty:(nullable NSDictionary *)property;
/// Create page
///
/// Call before `-startViewWithName`, this method is used to record the page load time, if the load time cannot be obtained, this method can be omitted.
/// - Parameters:
/// - viewName: Page name
/// - loadTime: Page load time (ns)
open func onCreateView(_ viewName: String, loadTime: NSNumber)
/// Enter page
/// - Parameters:
/// - viewName: Page name
/// - property: Event custom attributes (optional)
open func startView(withName viewName: String, property: [AnyHashable : Any]?)
/// Update the current RUM View load time.
/// Must be called between `-startView` and `-stopView` to take effect.
/// - Parameter duration: Load duration (nanoseconds).
open func updateViewLoadingTime(_ duration: NSNumber)
/// Leave page
/// - Parameter property: Event custom attributes (optional)
open func stopView(withProperty property: [AnyHashable : Any]?)
Code Example¶
- (void)viewDidAppear:(BOOL)animated{
[super viewDidAppear:animated];
// Scenario 1:
[[FTExternalDataManager sharedManager] startViewWithName:@"TestVC"];
// Scenario 2: Dynamic parameters
[[FTExternalDataManager sharedManager] startViewWithName:@"TestVC" property:@{@"custom_key":@"custom_value"}];
}
-(void)viewDidDisappear:(BOOL)animated{
[super viewDidDisappear:animated];
// Scenario 1:
[[FTExternalDataManager sharedManager] stopView];
// Scenario 2: Dynamic parameters
[[FTExternalDataManager sharedManager] stopViewWithProperty:@{@"custom_key":@"custom_value"}];
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// Scenario 1:
FTExternalDataManager.shared().startView(withName: "TestVC")
// Scenario 2: Dynamic parameters
FTExternalDataManager.shared().startView(withName: "TestVC",property: ["custom_key":"custom_value"])
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
// Scenario 1:
FTExternalDataManager.shared().stopView()
// Scenario 2: Dynamic parameters
FTExternalDataManager.shared().stopView(withProperty: ["custom_key":"custom_value"])
}
Action¶
Usage¶
/// Start RUM Action.
///
/// RUM will bind the Resource, Error, LongTask events that this Action may trigger. Avoid adding multiple times within 0.1 s, only one Action will be associated with the same View at the same time, new Actions will be discarded if the previous Action has not ended.
/// Does not affect the Action added by the `addAction:actionType:property` method.
///
/// - Parameters:
/// - actionName: Event name
/// - actionType: Event type
/// - property: Event custom attributes (optional)
- (void)startAction:(NSString *)actionName actionType:(NSString *)actionType property:(nullable NSDictionary *)property;
/// Add Action event. No duration, no discard logic
///
/// Does not affect the RUM Action started by `startAction:actionType:property:`.
/// - Parameters:
/// - actionName: Event name
/// - actionType: Event type
/// - property: Event custom attributes (optional)
- (void)addAction:(NSString *)actionName actionType:(NSString *)actionType property:(nullable NSDictionary *)property;
/// Start RUM Action.
///
/// RUM will bind the Resource, Error, LongTask events that this Action may trigger. Avoid adding multiple times within 0.1 s, only one Action will be associated with the same View at the same time, new Actions will be discarded if the previous Action has not ended.
/// Does not affect the Action added by the `addAction:actionType:property` method.
///
/// - Parameters:
/// - actionName: Event name
/// - actionType: Event type
/// - property: Event custom attributes (optional)
open func startAction(_ actionName: String, actionType: String, property: [AnyHashable : Any]?)
/// Add Action event. No duration, no discard logic
///
/// Does not affect the RUM Action started by `startAction:actionType:property:`.
/// - Parameters:
/// - actionName: Event name
/// - actionType: Event type
/// - property: Event custom attributes (optional)
open func addAction(_ actionName: String, actionType: String, property: [AnyHashable : Any]?)
Code Example¶
Error¶
Usage¶
```objectivec /// Add Error event /// - Parameters: /// - type: error type /// - message: Error message /// - stack: Stack information /// - property: Event custom attributes (optional) - (void)addErrorWithType:(NSString *)type message:(NSString *)message stack:(NSString *)stack property:(nullable NSDictionary *)property;
/// Add Error event /// - Parameters: /// - type: error type /// - state: Program running state /// - message: Error message /// - stack: Stack information /// - property: Event custom attributes (optional) - (