Custom Data Collection Rules¶
View¶
To customize automatic collection rules for UIKit Views, enable the configuration FTRumConfig.enableTraceUserView = YES.
rumConfig.viewTrackingHandler = [CustomViewTracker new];
#import "FTDefaultUIKitViewTrackingHandler.h"
// Example protocol implementation
@interface CustomViewTracker : NSObject <FTUIKitViewTrackingHandler>
// Add only when SDK default View collection rules are needed
@property (nonatomic, strong) FTDefaultUIKitViewTrackingHandler defaultHandler;
@end
@implementation CustomViewTracker
// Add only when SDK default View collection rules are needed
-(FTDefaultUIKitViewTrackingHandler *)defaultHandler{
if (!_defaultHandler) {
_defaultHandler = [FTDefaultUIKitViewTrackingHandler new];
}
return _defaultHandler;
}
- (FTRUMView *)rumViewForViewController:(UIViewController *)viewController {
// Exact match by class name
if ([viewController isKindOfClass:[HomeViewController class]]) {
return [[FTRUMView alloc] initWithViewName:@"main_home" property:@{@"page_type": @"home"}];
}
// Filter by prefix
else if ([NSStringFromClass([viewController class]) hasPrefix:@"FT"]) {
return [[FTRUMView alloc] initWithViewName:[NSString stringWithFormat:@"ft_%@", NSStringFromClass([viewController class])] property:nil];
}
// Set via accessibilityLabel
else if (viewController.view.accessibilityLabel) {
return [[FTRUMView alloc] initWithViewName:viewController.view.accessibilityLabel property:nil];
}
// After customizing some pages, use SDK default collection rules for remaining pages (return the default handler's processing result)
return [self.defaultHandler rumViewForViewController:viewController];
// To skip tracking, return nil directly
return nil;
}
@end
rumConfig.viewTrackingHandler = CustomViewTracker()
class CustomViewTracker: NSObject, FTUIKitViewTrackingHandler {
// Keep this property only when SDK default View collection rules are needed
lazy var defaultHandler: FTDefaultUIKitViewTrackingHandler = {
FTDefaultUIKitViewTrackingHandler()
}()
func rumView(for viewController: UIViewController) -> FTRUMView? {
// Exact match by class name
if viewController is HomeViewController {
let properties: [String: Any] = ["page_type": "home"]
return FTRUMView(viewName: "main_home", property: properties)
}
// Filter by class name prefix
let vcClassName = String(describing: type(of: viewController))
if vcClassName.hasPrefix("FT") {
let viewName = "ft_\(vcClassName)"
return FTRUMView(viewName: viewName, property: nil)
}
// Set via accessibilityLabel
if let accessibilityLabel = viewController.view.accessibilityLabel, !accessibilityLabel.isEmpty {
return FTRUMView(viewName: accessibilityLabel, property: nil)
}
// After customizing some pages, use SDK default collection rules for remaining pages (return the default handler's processing result)
return defaultHandler.rumView(for: viewController)
// To skip tracking, return nil directly
return nil
}
}
Page Load Time Collection Control¶
Supported since SDK 1.6.9.
By setting FTRumConfig before starting RUM, you can keep View auto-tracking and disable only automatic collection of page loading_time. enableTraceUserViewLoadingTime defaults to YES and takes effect when enableTraceUserView = YES; setting it to NO globally disables automatic load time collection without affecting manual load time reporting.
If you only need to exclude specific controllers, keep the global switch enabled and set viewLoadingTimeClassNameExcludes. For example, exclude HomeViewController in the project:
The class name array is empty by default. Matching uses the full, case-sensitive runtime class name. For Swift classes, use NSStringFromClass(HomeViewController.self) to obtain the exact name and avoid missing the module name prefix. Substrings, regular expressions, or subclasses are not matched, and custom View Names returned by viewTrackingHandler are not used. Excluded controllers still collect RUM View; when overriding lifecycle methods, call the corresponding super method.
SwiftUI View Auto-Collection (Experimental)¶
SwiftUI View auto-collection first extracts the page name through the SDK, then determines whether to generate RUM View through FTRumConfig.swiftUIViewTrackingHandler. You can use the default handler to enable it directly, or implement FTSwiftUIViewTrackingHandler to filter the extracted SwiftUI View Names and customize the reported View Names and properties.
To explicitly control the page name and lifecycle in a specific SwiftUI View, see SwiftUI View Manual Collection.
Note: SwiftUI View auto-collection is currently an experimental feature. Related APIs and collection behavior may change in later versions.
Before use, enable FTRumConfig.enableTraceUserView and set FTRumConfig.swiftUIViewTrackingHandler.
To customize SwiftUI View collection rules, implement FTSwiftUIViewTrackingHandler. Returning FTRUMView collects the SwiftUI View; returning nil skips it.
rumConfig.swiftUIViewTrackingHandler = [CustomSwiftUIViewTracker new];
@interface CustomSwiftUIViewTracker : NSObject <FTSwiftUIViewTrackingHandler>
@end
@implementation CustomSwiftUIViewTracker
- (nullable FTRUMView *)rumViewForExtractedViewName:(NSString *)extractedViewName {
if ([extractedViewName isEqualToString:@"HomeView"]) {
return [[FTRUMView alloc] initWithViewName:@"main_home" property:@{@"page_type": @"home"}];
}
return nil;
}
@end
rumConfig.swiftUIViewTrackingHandler = CustomSwiftUIViewTracker()
class CustomSwiftUIViewTracker: NSObject, FTSwiftUIViewTrackingHandler {
func rumView(forExtractedViewName extractedViewName: String) -> FTRUMView? {
if extractedViewName == "HomeView" {
return FTRUMView(
viewName: "main_home",
property: ["page_type": "home"]
)
}
return nil
}
}
View Timing Metrics¶
Supported in SDK 1.6.8+
When View and related Action / Resource data are already being collected, the SDK automatically calculates the following optional metrics without a separate enable switch. For manual collection, call the corresponding start/end APIs at the actual event boundaries.
| Metric | Unit | Definition and Default Rules |
|---|---|---|
interaction_to_next_view_time (INV) |
Nanoseconds | The current View start time minus the start time of the nearest eligible Action within the immediately preceding View in the same Session. By default, only click is matched, and the interval must be within [0, 3 seconds]. |
network_settled_time (TNS) |
Nanoseconds | The latest valid end time among initial network requests minus the current View start time. By default, initial requests start within [0, 100 ms] after the View starts. |
The starting point here is RUM View start, not the load start point of loading_time. The 100 ms for TNS is the filtering range for request start, not waiting for "network idle for 100 ms". Completed batches of initial requests can produce results first, and subsequent eligible batches may update the value for the same View after completion.
When there is no eligible Action, no valid initial request interval, or data is filtered out, the corresponding metric is absent. Missing values should not be treated as 0. A valid zero duration can be reported. INV is not correlated across Sessions; fallback Views (such as synthesized launch or background Views) do not generate these two metrics. TNS does not produce a value when the calculation interval enters the background or when usable state history is missing.
You can adjust the default rule time thresholds before RUM initialization. Constructor parameters are all in nanoseconds:
rumConfig.nextViewActionPredicate = [[FTRUMTimeBasedNextViewActionPredicate alloc]
initWithMaxTimeNs:5000000000LL]; // click, maximum 5 seconds
rumConfig.networkSettledResourcePredicate = [[FTRUMTimeBasedNetworkSettledPredicate alloc]
initWithThresholdNs:200000000LL]; // Requests started within 200 ms after View start
The nil behavior differs between the two properties: nextViewActionPredicate = nil disables INV; networkSettledResourcePredicate = nil restores the default 100 ms rule. The INV configuration API does not support App Extensions.
To filter by Action name, next page, or request URL, implement the public protocols. The following example matches only open_checkout clicks entering Checkout and treats only specified API requests as initial requests:
@interface CheckoutTimingRules : NSObject <FTRUMNextViewActionPredicate, FTRUMNetworkSettledResourcePredicate>
@end
@implementation CheckoutTimingRules
- (BOOL)isLastAction:(FTRUMNextViewActionParams *)params {
return [params.actionType isEqualToString:@"click"] &&
[params.actionName isEqualToString:@"open_checkout"] &&
[params.nextViewName isEqualToString:@"Checkout"] &&
params.timeToNextViewNs >= 0 && params.timeToNextViewNs <= 3000000000LL;
}
- (BOOL)isInitialResource:(FTRUMNetworkSettledResourceParams *)params {
return [params.resourceURL hasPrefix:@"https://api.example.com/"] &&
params.timeSinceViewStartNs >= 0 && params.timeSinceViewStartNs <= 100000000LL;
}
@end
// Set before initializing RUM.
CheckoutTimingRules *rules = [[CheckoutTimingRules alloc] init];
rumConfig.nextViewActionPredicate = rules;
rumConfig.networkSettledResourcePredicate = rules;
final class CheckoutTimingRules: NSObject, FTRUMNextViewActionPredicate, FTRUMNetworkSettledResourcePredicate {
func isLastAction(_ params: FTRUMNextViewActionParams) -> Bool {
params.actionType == "click" && params.actionName == "open_checkout" &&
params.nextViewName == "Checkout" &&
params.timeToNextViewNs >= 0 && params.timeToNextViewNs <= 3_000_000_000
}
func isInitialResource(_ params: FTRUMNetworkSettledResourceParams) -> Bool {
(params.resourceURL?.hasPrefix("https://api.example.com/") ?? false) &&
params.timeSinceViewStartNs >= 0 && params.timeSinceViewStartNs <= 100_000_000
}
}
// Set before initializing RUM.
let rules = CheckoutTimingRules()
rumConfig.nextViewActionPredicate = rules
rumConfig.networkSettledResourcePredicate = rules
Callbacks run on the RUM background queue and must be fast, thread-safe, and return consistent results for the same input. They must not access the UI, initiate network requests, or perform blocking waits; resourceURL may be empty. Rules can only select data that is actually collected and passes filtering; they do not backfill new Actions or Resources.
Action¶
Enable the configuration FTRumConfig.enableTraceUserAction = YES.
SDK Initialization Timing¶
It is recommended to initialize the base SDK on the main thread before starting RUM: for UIKit, place it at the beginning of the application:didFinishLaunchingWithOptions: method; for SwiftUI, place it in App.init(). For a complete example, see Quick Start.
Launch Timing Phases¶
After enabling enableTraceUserAction, the SDK automatically collects initial launch (launch_cold / launch_warm) and hot launch (launch_hot). Initial launch is reported only once per process. After shutdown and re-initialization, hot launch continues to be collected.
| Phase | Interval |
|---|---|
| Pre Runtime Init | app_pre_runtime_init_time: From process creation to runtime initialization (SDK's +load). |
| Runtime Init to Pre Main Initializers | app_runtime_init_time: From runtime initialization to pre-main initialization (SDK's constructor). |
| UIKit Init | app_uikit_init_time: From pre-main initialization to starting the base SDK. |
| Application Init | app_application_init_time: From starting the base SDK to receiving the UIApplicationDidFinishLaunchingNotification notification. |
| Initial Frame Render | app_first_frame_init_time: From the launch completion notification to the frame time corresponding to the first CADisplayLink callback. |
The start and duration fields in the phases are in nanoseconds, representing the offset relative to the launch Action time and the phase duration, respectively. When collection starts later than first activation, first activation is used as the endpoint, and the last three phases are not output.
Launch Prewarm Detection and Timing Calibration¶
Supported since SDK 1.6.9; iOS only.
iOS may create a process and complete some launch preparation before the user opens the app. This mechanism is called Prewarm. The wait between prewarm and the actual launch may make the measured launch time too large.
The SDK recognizes system prewarm and calibrates launch time. You can also set rumConfig.launchPrewarmInterval = 1500 before starting RUM to enable custom timing inference. The unit is milliseconds, and the default is 0 (custom inference disabled). The handling rules are as follows:
- System prewarm: Automatically recognized; the pre-runtime and runtime phases are ignored, and calculation starts from constructor. This is not controlled by the above configuration.
- Manual detection interval exceeds threshold: The first three phases are ignored, and calculation starts from SDK initialization.
- pre-runtime exceeds threshold: When the manual rule is not matched, only pre-runtime is ignored, and calculation starts from SDK
+load.
Custom checks use a strictly greater-than threshold condition. After calibration, the Action time, total duration, and phase start use the new starting point; if a valid starting point cannot be obtained, the original duration is retained. Prewarm launches are reported as launch_warm; when configured to a positive value, prewarm_type distinguishes system / custom.
To add manual detection, add the following in the native lifecycle:
- Call
[FTSDKAgent prewarmCheckStart]at themainentry. - Call
[FTSDKAgent prewarmCheckEnd]at the beginning of theapplication:willFinishLaunchingWithOptions:method.
The corresponding Swift calls are FTSDKAgent.prewarmCheckStart() and FTSDKAgent.prewarmCheckEnd(). Both calls should complete before SDK initialization.
If the app adds its own business logic between the main entry and the application:willFinishLaunchingWithOptions: callback, do not use the manual detection APIs above. Otherwise, business execution time may be misclassified as prewarm waiting and the launch time may be incorrectly trimmed.
Timing inference may misclassify a genuinely slow launch as prewarm. Compare data before and after enabling it; the calibration result is not equivalent to user-perceived launch time.
Custom Action Collection¶
rumConfig.actionTrackingHandler = [CustomActionTracker new];
#import "FTDefaultActionTrackingHandler.h"
// Example protocol implementation
// In the iOS environment, conform to the `FTUIPressRUMActionsHandler` protocol
// In the tvOS environment, conform to the `FTUITouchRUMActionsHandler` protocol.
@interface CustomActionTracker : NSObject <FTUIPressRUMActionsHandler,FTUITouchRUMActionsHandler>
// Add only when SDK default Action collection rules are needed
@property (nonatomic, strong) FTDefaultActionTrackingHandler defaultHandler;
@end
@implementation CustomActionTracker
// Add only when SDK default Action collection rules are needed
-(FTDefaultActionTrackingHandler *)defaultHandler{
if (!_defaultHandler) {
_defaultHandler = [FTDefaultActionTrackingHandler new];
}
return _defaultHandler;
}
// Protocol method required by both iOS and tvOS
- (nullable FTRUMAction *)rumLaunchActionWithLaunchType:(FTLaunchType)type {
if(type == FTLaunchCold){
return [[FTRUMAction alloc]initWithActionName:@"cold"];
}
// Return nil to skip tracking
return nil;
}
// Protocol method required in the iOS environment
-(nullable FTRUMAction *)rumActionWithTargetView:(UIView *)targetView{
if (view.accessibilityIdentifier){
return [[FTRUMAction alloc] initWithActionName:view.accessibilityIdentifier];
}
// After customizing some Actions, use SDK default collection rules for the rest (return the default handler's processing result)
return [self.defaultHandler rumActionWithTargetView:targetView];
// Return nil to skip tracking
return nil;
}
// Protocol method required in the tvOS environment
- (nullable FTRUMAction *)rumActionWithPressType:(UIPressType)type targetView:(UIView *)targetView{
if (type == UIPressTypeSelect && view.accessibilityIdentifier){
return [[FTRUMAction alloc] initWithActionName:view.accessibilityIdentifier];
}
// After customizing some Actions, use SDK default collection rules for the rest (return the default handler's processing result)
return [self.defaultHandler rumActionWithPressType:type targetView:targetView];
// Return nil to skip tracking
return nil;
}
@end
rumConfig.actionTrackingHandler = CustomActionTracker()
// Example protocol implementation
// In the iOS environment, conform to the `FTUIPressRUMActionsHandler` protocol
// In the tvOS environment, conform to the `FTUITouchRUMActionsHandler` protocol.
class CustomActionTracker: NSObject, FTUIPressRUMActionsHandler, FTUITouchRUMActionsHandler {
// Add only when SDK default Action collection rules are needed
lazy var defaultHandler: FTDefaultActionTrackingHandler = {
FTDefaultActionTrackingHandler()
}()
// Protocol method required by both iOS and tvOS
func rumLaunchAction(with type: FTLaunchType) -> FTRUMAction? {
if type == .cold {
return FTRUMAction(actionName: "cold")
}
// Return nil to skip tracking
return nil
}
// Protocol method required in the iOS environment
func rumAction(withTargetView targetView: UIView) -> FTRUMAction? {
if let identifier = targetView.accessibilityIdentifier {
return FTRUMAction(actionName: identifier)
}
// After customizing some Actions, use SDK default collection rules for the rest (return the default handler's processing result)
return defaultHandler.rumAction(withTargetView: targetView)
// Return nil to skip tracking
return nil
}
// Protocol method required in the tvOS environment
func rumAction(with pressType: UIPress.PressType, targetView: UIView) -> FTRUMAction? {
if pressType == .select, let identifier = targetView.accessibilityIdentifier {
return FTRUMAction(actionName: identifier)
}
// After customizing some Actions, use SDK default collection rules for the rest (return the default handler's processing result)
return defaultHandler.rumAction(with: pressType, targetView: targetView)
// Return nil to skip tracking
return nil
}
}
Resource¶
Enable the configuration FTRUMConfig.enableTraceUserResource = YES or Customize Network Collection by Forwarding URLSession Delegate.
Filter Collection by URL¶
Add Custom Properties¶
By setting a property provider closure, you can return additional properties to attach to RUM Resource.
For example, you may want to add the HTTP request body to RUM Resource:
rumConfig.resourcePropertyProvider = ^NSDictionary *_Nullable(NSURLRequest *request, NSURLResponse *response,NSData *data, NSError *error) {
NSString *body = @"";
if (request.HTTPBody) {
body = [[NSString alloc] initWithData:httpBody encoding:NSUTF8StringEncoding] ?: @"";
}
return @{@"request_body": body};
}
Filter Network Errors¶
When a network request error occurs, RUM generates an Error of type network_error. Some URLSession local errors, such as task.cancel, are normal logic in the user's program and are not error data. In this case, you can intercept and filter them through the sessionTaskErrorFilter callback. Return YES to intercept and NO not to intercept. After interception, RUM Error does not collect that error.
Error¶
Through FTRumConfig.issueDataProvider, when the SDK automatically collects Crash or ANR, you can add business fields to the corresponding RUM Error based on the information of this exception, such as business scenario, feature module, or experiment group. This capability is supported in SDK 1.6.7 and later.
issueDataProvider only adds fields for automatically collected Crash and ANR; it does not enable Crash or ANR monitoring. Before use, enable enableTrackAppCrash or enableTrackAppANR according to the collection target.
Configuration¶
Set issueDataProvider before starting RUM. Modifying the original FTRumConfig after RUM starts does not change the currently running Provider.
FTRumConfig *rumConfig = [[FTRumConfig alloc] initWithAppid:appid];
rumConfig.enableTrackAppCrash = YES;
rumConfig.enableTrackAppANR = YES;
// Prepare a read-only business snapshot before starting RUM to avoid time-consuming operations in the callback.
NSDictionary<NSString *, id> *businessContext = @{
@"business_scene": @"checkout",
@"release_channel": @"app_store"
};
rumConfig.issueDataProvider = ^NSDictionary<NSString *, id> * _Nullable(FTIssueInfo *issue) {
NSMutableDictionary<NSString *, id> *fields = [businessContext mutableCopy];
fields[@"issue_category"] =
issue.category == FTIssueCategoryCrash ? @"crash" : @"anr";
fields[@"historical_issue"] = @(issue.isHistorical);
if (issue.threadName.length > 0) {
fields[@"issue_thread_name"] = issue.threadName;
}
return fields;
};
[[FTMobileAgent sharedInstance] startRumWithConfigOptions:rumConfig];
let rumConfig = FTRumConfig(appid: appid)
rumConfig.enableTrackAppCrash = true
rumConfig.enableTrackAppANR = true
// Prepare a read-only business snapshot before starting RUM to avoid time-consuming operations in the callback.
let businessContext: [String: Any] = [
"business_scene": "checkout",
"release_channel": "app_store"
]
rumConfig.issueDataProvider = { issue in
var fields = businessContext
fields["issue_category"] =
issue.category == .crash ? "crash" : "anr"
fields["historical_issue"] = issue.isHistorical
if let threadName = issue.threadName, !threadName.isEmpty {
fields["issue_thread_name"] = threadName
}
return fields
}
FTMobileAgent.sharedInstance().startRum(withConfigOptions: rumConfig)
The Provider is called synchronously once for each eligible automatically collected Error. Returning nil or an empty dictionary means no custom fields are added for this occurrence.
FTIssueInfo¶
The callback parameter FTIssueInfo is a read-only object that describes the Crash or ANR currently being processed.
| Property | Type | Description |
|---|---|---|
| category | FTIssueCategory | Exception category: FTIssueCategoryCrash / Swift .crash indicates Crash, FTIssueCategoryANR / Swift .anr indicates ANR |
| errorType | NSString | Type corresponding to RUM Error. Crash is ios_crash, ANR is anr_error |
| message | NSString | Error message; nil if unavailable |
| stack | NSString | Exception stack |
| occurredAtNanoseconds | long long | Exception occurrence time, Unix timestamp in nanoseconds |
| appState | NSString | App state used by the corresponding RUM Error |
| threadName | NSString | Exception thread name; nil if unavailable |
| historical | BOOL | Whether the exception is restored from persisted data; Objective-C getter is isHistorical, Swift uses isHistorical |
The mapping of category, errorType, and historical in automatic collection scenarios is as follows:
| Scenario | category | errorType | historical |
|---|---|---|---|
| Crash report restored on the app's next launch | Crash | ios_crash |
YES |
| ANR after recovery in the current process | ANR | anr_error |
NO |
| Watchdog ANR from the previous process restored on the app's next launch | ANR | anr_error |
YES |
When historical is YES, the exception time, stack, and app state in FTIssueInfo come from persisted exception data, but the Provider executes only when the app recovers and processes the report. Therefore, business state directly read at Provider runtime belongs to the current process and is not necessarily the state when the exception occurred. To correlate business information at exception time, persist it in advance and load it as a thread-safe in-memory snapshot before starting RUM; do not perform disk reads in the Provider.
Custom Field Rules¶
Fields returned by the Provider are written to the fields of the corresponding RUM Error, not to tags. Fields must meet the following rules:
- Key must be a non-empty string, and its UTF-8 encoded length must not exceed 100 bytes.
- Values support only strings, booleans, integers, and finite floating-point numbers; arrays, dictionaries,
NSNull, and custom objects are not supported. - The UTF-8 encoded length of a string Value must not exceed 4096 bytes.
- The SDK scans at most the first 50 entries in the returned dictionary; invalid fields also count toward the scan limit. Dictionary iteration order is not fixed, so return no more than 50 entries.
- The estimated total size of all accepted fields must not exceed 25 KiB.
- Keys starting with
error.orerror_are ignored. - If a custom field has the same name as an existing SDK tag or field, the SDK field takes precedence.
Fields that do not comply with the rules are ignored and do not prevent collection and reporting of the original Crash or ANR Error. Custom fields are uploaded with RUM data; do not include sensitive information such as passwords or Tokens.
Callback Execution Requirements¶
issueDataProvider may execute concurrently or reentrantly on non-main threads. Callbacks should meet the following requirements:
- Ensure thread safety, and prefer reading prepared immutable data or in-memory snapshots.
- Return within 10 ms.
- Do not operate the UI or perform network or disk I/O.
- Do not perform blocking operations such as thread switching, synchronous dispatch, or long lock waits.
When execution takes longer than 50 ms, the SDK may output a slow callback debug log but still continues processing the original RUM Error.
Applicable Scope¶
issueDataProvider applies to Crash automatically collected by the SDK, ANR after recovery in the current process, and Watchdog ANR from the previous process. The following data does not trigger this Provider:
- Errors manually added through APIs such as
addError - Resource / Network Error
- WebView Error
- Long Task
- Data upload or retry process
Custom TraceHeader¶
You can configure globally through FTTraceConfig.traceInterceptor, or Customize Trace at URLSession Level. The following uses w3c-traceContext as an example.
FTTraceConfig *traceConfig = [[FTTraceConfig alloc]init];
traceConfig.traceInterceptor = ^FTTraceContext * _Nullable(NSURLRequest *request) {
// 1. Get the business-defined traceId
NSString *replaceTrace = [request.allHTTPHeaderFields valueForKey:CUSTOM_TRACE_HEADER];
// 2. Get the SDK standard W3C traceparent request header
NSDictionary *traceHeaders = [[FTExternalDataManager sharedManager] getTraceHeaderWithUrl:request.URL];
NSString *traceParentStr = traceHeaders[FT_NETWORK_TRACEPARENT_KEY];
// 3. Parse the W3C traceparent format and replace the traceId at index 1
NSArray *traceComponents = [traceParentStr componentsSeparatedByString:@"-"];
if (traceComponents.count != 4) {
return nil;
}
NSMutableArray *newComponents = [traceComponents mutableCopy];
newComponents[1] = replaceTrace;
NSString *newTraceParent = [newComponents componentsJoinedByString:@"-"];
// 4. Assemble and return the custom tracing context
FTTraceContext *context = [FTTraceContext new];
context.traceHeader = @{FT_NETWORK_TRACEPARENT_KEY:newTraceParent};
context.traceId = replaceTrace;
// Preserve the SDK-generated spanId (index 2 is a fixed position)
context.spanId = newComponents[2];
return context;
};
let traceConfig = FTTraceConfig()
traceConfig.traceInterceptor = { (request: URLRequest) -> FTTraceContext? in
// 1. Get the business-defined traceId
guard let replaceTrace = request.allHTTPHeaderFields?[CUSTOM_TRACE_HEADER] else {
return nil
}
// 2. Get the SDK standard W3C traceparent request header
guard let traceHeaders = FTExternalDataManager.shared().getTraceHeader(with: request.url!), let traceParentStr = traceHeaders[FT_NETWORK_TRACEPARENT_KEY] as? String else {
return nil
}
// 3. Parse the W3C traceparent format and replace the traceId at index 1
let traceComponents = traceParentStr.components(separatedBy: "-")
guard traceComponents.count == 4 else {
return nil
}
var newComponents = traceComponents
newComponents[1] = replaceTrace
let newTraceParent = newComponents.joined(separator: "-")
// 4. Assemble and return the custom tracing context
let context = FTTraceContext()
context.traceHeader = [FT_NETWORK_TRACEPARENT_KEY: newTraceParent]
context.traceId = replaceTrace
// Preserve the SDK-generated spanId (index 2 is a fixed position)
context.spanId = newComponents[2]
return context
}