Skip to content

Custom Data Collection Rules

View

To customize automatic UIKit View tracking rules, enable the FTRumConfig.enableTraceUserView = YES configuration.

rumConfig.viewTrackingHandler = [CustomViewTracker new];

#import "FTDefaultUIKitViewTrackingHandler.h"

// Example of implementing the protocol
@interface CustomViewTracker : NSObject <FTUIKitViewTrackingHandler>
// Only add this if you need the SDK's default View tracking rules
@property (nonatomic, strong) FTDefaultUIKitViewTrackingHandler defaultHandler;
@end

@implementation CustomViewTracker

// Only add this if you need the SDK's default View tracking rules
-(FTDefaultUIKitViewTrackingHandler *)defaultHandler{
    if (!_defaultHandler) {
        _defaultHandler = [FTDefaultUIKitViewTrackingHandler new];
    }
    return _defaultHandler;
}

- (FTRUMView *)rumViewForViewController:(UIViewController *)viewController {
    // Match exactly by class name
    if ([viewController isKindOfClass:[HomeViewController class]]) {
        return [[FTRUMView alloc] initWithViewName:@"main_home" property:@{@"page_type": @"home"}];
    }
    // Filter by class name prefix
    else if ([NSStringFromClass([viewController class]) hasPrefix:@"FT"]) {
        return [[FTRUMView alloc] initWithViewName:[NSString stringWithFormat:@"ft_%@", NSStringFromClass([viewController class])] property:nil];
    }
    // Use the accessibilityLabel to set the View name
    else if (viewController.view.accessibilityLabel) {
        return [[FTRUMView alloc] initWithViewName:viewController.view.accessibilityLabel property:nil];
    }
    // After customizing some pages, use the SDK default tracking rules for the remaining pages (return the result from the default handler)
    return [self.defaultHandler rumViewForViewController:viewController];

    // If you need to skip tracking, return nil directly
    return nil;
}
@end
rumConfig.viewTrackingHandler = CustomViewTracker()

class CustomViewTracker: NSObject, FTUIKitViewTrackingHandler {

    // Keep this property only if you need the SDK's default View tracking rules
    lazy var defaultHandler: FTDefaultUIKitViewTrackingHandler = {
        FTDefaultUIKitViewTrackingHandler() 
    }()

    func rumView(for viewController: UIViewController) -> FTRUMView? {
        // Match exactly 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)
        }

        // Use the accessibilityLabel to set the View name
        if let accessibilityLabel = viewController.view.accessibilityLabel, !accessibilityLabel.isEmpty {
            return FTRUMView(viewName: accessibilityLabel, property: nil)
        }

        // After customizing some pages, use the SDK default tracking rules for the remaining pages (return the result from the default handler)
        return defaultHandler.rumView(for: viewController)

        // If you need to skip tracking, return nil directly
        return nil
    }
}

SwiftUI View Auto Tracking (Experimental)

SwiftUI View auto-tracking first lets the SDK extract the page name, and then uses FTRumConfig.swiftUIViewTrackingHandler to decide whether a RUM View is generated. You can enable it directly with the default handler, or implement FTSwiftUIViewTrackingHandler to filter the extracted SwiftUI View Name and customize the reported View Name and attributes.

To explicitly control the page name and lifecycle for a specific SwiftUI View, see SwiftUI View Manual Tracking.

Note: SwiftUI View auto-tracking is currently an experimental feature. The related APIs and tracking behavior may change in future versions.

Before using it, enable FTRumConfig.enableTraceUserView and set FTRumConfig.swiftUIViewTrackingHandler.

rumConfig.enableTraceUserView = YES;
rumConfig.swiftUIViewTrackingHandler = [FTDefaultSwiftUIViewTrackingHandler new];
rumConfig.enableTraceUserView = true
rumConfig.swiftUIViewTrackingHandler = FTDefaultSwiftUIViewTrackingHandler()

To customize SwiftUI View tracking rules, implement FTSwiftUIViewTrackingHandler. Returning an FTRUMView tracks that 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 since SDK 1.6.8+

When an existing View has associated Action / Resource data collected, the SDK automatically calculates the following optional metrics. No separate enable switch is required. For manual tracking, 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's start time minus the start time of the most recent qualifying Action in the immediately preceding View of the same Session. Only click is matched by default, and the interval must be within [0, 3s]
network_settled_time (TNS) Nanoseconds The latest valid end time among initial network requests minus the current View's start time. By default, initial requests must start within [0, 100ms] after the View starts

The reference point here is the start of the RUM View, not the loading start point of loading_time. The 100ms in TNS is the filter window for when requests start, not a wait for "100ms of network idle time". A completed batch of initial requests can produce a result first; a later qualifying batch may update the same View's value when it completes.

If there is no qualifying Action, no valid initial request interval, or the data was filtered, the corresponding metric does not appear. A missing metric should not be treated as 0. A legitimate zero duration can be reported. INV is not associated across Sessions; fallback Views (such as synthesized launch or background Views) do not produce these two metrics. TNS does not produce a value if the calculation interval crosses into the background or if no usable state history is available.

You can adjust the time thresholds of the default rules before initializing RUM. Constructor parameters are in nanoseconds:

rumConfig.nextViewActionPredicate = [[FTRUMTimeBasedNextViewActionPredicate alloc]
    initWithMaxTimeNs:5000000000LL]; // click, max 5 seconds
rumConfig.networkSettledResourcePredicate = [[FTRUMTimeBasedNetworkSettledPredicate alloc]
    initWithThresholdNs:200000000LL]; // Requests started within 200ms after the View starts
rumConfig.nextViewActionPredicate = FTRUMTimeBasedNextViewActionPredicate(maxTimeNs: 5_000_000_000)
rumConfig.networkSettledResourcePredicate = FTRUMTimeBasedNetworkSettledPredicate(thresholdNs: 200_000_000)

The two properties have different nil behavior: setting nextViewActionPredicate = nil disables INV; setting networkSettledResourcePredicate = nil restores the default 100ms rule. The INV configuration API is not supported in App Extensions.

To filter by Action name, next page, or request URL, implement the public protocols. The following example only matches the open_checkout click that enters Checkout, and only treats the 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

// Configure 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
    }
}

// Configure before initializing RUM.
let rules = CheckoutTimingRules()
rumConfig.nextViewActionPredicate = rules
rumConfig.networkSettledResourcePredicate = rules

Callbacks run on the RUM background queue. They must be fast, thread-safe, and return consistent results for the same input. Do not access the UI, make network requests, or block on waits. resourceURL may be nil. The rules can only select data that was actually collected and passed filtering; they cannot collect new Actions or Resources.

Action

Enable the FTRUMConfig.enableTraceUserAction = YES configuration.

rumConfig.actionTrackingHandler = [CustomActionTracker new];

#import "FTDefaultActionTrackingHandler.h"

// Example of implementing the protocol
// On iOS, conform to the `FTUIPressRUMActionsHandler` protocol
// On tvOS, conform to the `FTUITouchRUMActionsHandler` protocol.
@interface CustomActionTracker : NSObject <FTUIPressRUMActionsHandler,FTUITouchRUMActionsHandler>
// Only add this if you need the SDK's default Action tracking rules
@property (nonatomic, strong) FTDefaultActionTrackingHandler defaultHandler;
@end
@implementation CustomActionTracker

// Only add this if you need the SDK's default Action tracking rules
-(FTDefaultActionTrackingHandler *)defaultHandler{
    if (!_defaultHandler) {
        _defaultHandler = [FTDefaultActionTrackingHandler new];
    }
    return _defaultHandler;
}

// Protocol method required on 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 on iOS
-(nullable FTRUMAction *)rumActionWithTargetView:(UIView *)targetView{
    if (view.accessibilityIdentifier){
       return [[FTRUMAction alloc] initWithActionName:view.accessibilityIdentifier];
    }

     // After customizing some Actions, use the SDK default tracking rules for the rest (return the result from the default handler)
    return [self.defaultHandler rumActionWithTargetView:targetView];

    // Return nil to skip tracking
    return nil;
}
// Protocol method required on tvOS
- (nullable FTRUMAction *)rumActionWithPressType:(UIPressType)type targetView:(UIView *)targetView{
    if (type == UIPressTypeSelect && view.accessibilityIdentifier){
       return [[FTRUMAction alloc] initWithActionName:view.accessibilityIdentifier];
    }

    // After customizing some Actions, use the SDK default tracking rules for the rest (return the result from the default handler)
    return [self.defaultHandler rumActionWithPressType:type targetView:targetView];

        // Return nil to skip tracking
    return nil;
}
@end
rumConfig.actionTrackingHandler = CustomActionTracker()

// Example of implementing the protocol
// On iOS, conform to the `FTUIPressRUMActionsHandler` protocol
// On tvOS, conform to the `FTUITouchRUMActionsHandler` protocol.
class CustomActionTracker: NSObject, FTUIPressRUMActionsHandler, FTUITouchRUMActionsHandler {

    // Only add this if you need the SDK's default Action tracking rules
    lazy var defaultHandler: FTDefaultActionTrackingHandler = {
        FTDefaultActionTrackingHandler()
    }()

    // Protocol method required on 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 on iOS
    func rumAction(withTargetView targetView: UIView) -> FTRUMAction? {
        if let identifier = targetView.accessibilityIdentifier {
            return FTRUMAction(actionName: identifier)
        }

        // After customizing some Actions, use the SDK default tracking rules for the rest (return the result from the default handler)
        return defaultHandler.rumAction(withTargetView: targetView)

        // Return nil to skip tracking
        return nil 
    }

    // Protocol method required on tvOS
    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 the SDK default tracking rules for the rest (return the result from the default handler)        
        return defaultHandler.rumAction(with: pressType, targetView: targetView)

        // Return nil to skip tracking
        return nil
    }
}

Resource

Enable the FTRUMConfig.enableTraceUserResource = YES configuration, or customize Network tracking by forwarding URLSession Delegate.

Filter Collection by URL

rumConfig.resourceUrlHandler = ^(NSURL *url){
        // Return YES to skip collection; return NO to collect
        if ([url.host isEqualToString:@"example.com"]) {
            return YES;
        }
        return NO;
};
rumConfig.resourceUrlHandler = { url in 
     // Return true to skip collection; return false to collect
     return url.host == "example.com"
}

Add Custom Attributes

By setting the attribute provider closure, you can return additional attributes to attach to the RUM Resource.

For example, you may want to add the HTTP request body to the 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};
 }
rumConfig.resourcePropertyProvider = { request, response, data, error in
   let body = request.httpBody.flatMap { String(data: $0, encoding: .utf8) } ?? ""
   return ["request_body": body]
  }

Filter Network Errors

When a network request error occurs, RUM generates an Error data entry of type network_error. Some URLSession local errors, such as task cancellation, are normal logic in the user's program rather than error data. In this case, you can use the sessionTaskErrorFilter callback to intercept and filter them. Return YES to intercept, or NO not to intercept. After interception, the error is not collected as an RUM Error.

rumConfig.sessionTaskErrorFilter = ^BOOL(NSError * _Nonnull error){
    return error.code == NSURLErrorCancelled;
}; 
rumConfig.sessionTaskErrorFilter = { error in
   return (error as? URLError)?.code == .cancelled
}

Error

With FTRumConfig.issueDataProvider, when the SDK automatically collects a Crash or ANR, you can add business fields to the corresponding RUM Error based on the current exception information, such as business scenario, feature module, or experiment group. This capability is supported in SDK 1.6.7 and later.

issueDataProvider only adds fields to automatically collected Crashes and ANRs; it does not enable Crash or ANR monitoring. Before using it, enable enableTrackAppCrash or enableTrackAppANR according to what you want to collect.

Configuration

Set issueDataProvider before starting RUM. Modifying the original FTRumConfig after RUM starts does not change the Provider currently in use.

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 that call.

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 a Crash, FTIssueCategoryANR / Swift .anr indicates an ANR
errorType NSString The type of the corresponding RUM Error. Crash is ios_crash, ANR is anr_error
message NSString Error message, or nil if unavailable
stack NSString Exception stack trace
occurredAtNanoseconds long long Time when the exception occurred, Unix timestamp in nanoseconds
appState NSString The application state used by the corresponding RUM Error
threadName NSString Name of the exception thread, or nil if unavailable
historical BOOL Whether the exception was restored from persisted data; the Objective-C getter is isHistorical, and Swift uses isHistorical

The mapping of category, errorType, and historical in auto-collection scenarios is as follows:

Scenario category errorType historical
Crash report recovered on the next app launch Crash ios_crash YES
ANR recovered in the current process ANR anr_error NO
Watchdog ANR from the previous process recovered on the next app launch ANR anr_error YES

When historical is YES, the exception time, stack, and application state in FTIssueInfo come from persisted exception data, but the Provider is only executed when the app recovers and processes the report. Therefore, business state read directly while the Provider runs belongs to the current process and is not necessarily the state at the time the exception occurred. To associate business information from the time the exception occurred, persist it in advance and load it as a thread-safe in-memory snapshot before starting RUM. Do not perform disk reads inside the Provider.

Custom Field Rules

Fields returned by the Provider are written to the fields of the corresponding RUM Error, not to tags. The fields must satisfy the following rules:

  • The key must be a non-empty string, and its UTF-8 encoded length must not exceed 100 bytes.
  • Values only support 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 scanned entries. Since dictionary traversal order is not fixed, it is recommended to return no more than 50 entries.
  • The estimated total size of all accepted fields must not exceed 25 KiB.
  • Keys starting with error. or error_ 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 conform to these rules are ignored and do not prevent the original Crash or ANR Error from being collected and reported. Custom fields are uploaded with RUM data, so do not include sensitive information such as passwords or tokens.

Callback Execution Requirements

issueDataProvider may be called concurrently or reentrantly on a non-main thread. The callback should meet the following requirements:

  • Ensure the implementation is thread-safe, and prefer reading prepared immutable data or in-memory snapshots.
  • It is recommended to return within 10 ms.
  • Do not operate on the UI or perform network or disk I/O.
  • Avoid blocking operations such as thread switching, synchronous dispatch, or waiting on locks for a long time.

When execution takes longer than 50 ms, the SDK may output a slow-callback debug log, but it will still continue processing the original RUM Error.

Applicability

issueDataProvider applies to Crashes automatically collected by the SDK, ANRs recovered in the current process, and Watchdog ANRs from the previous process. The following data does not trigger the Provider:

  • Errors manually added through APIs such as addError
  • Resource / Network Errors
  • WebView Errors
  • Long Tasks
  • Data upload or retry processes

Custom TraceHeader

You can configure it globally through FTTraceConfig.traceInterceptor, or use URLSession-level custom Trace. 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;
    // Keep the SDK-generated spanId (fixed position at index 2)
    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
        // Keep the SDK-generated spanId (fixed position at index 2)
        context.spanId = newComponents[2]
        return context
    }